I have this
$number = 0.5
if (is_float($number))
{
echo 'float';
}
else
{
echo 'not float';
}
and it echos not float. what could be the reason thanks
Probably $number is actually a string: "0.5".
See is_numeric instead. The is_* family checks against the actual type of the variable. If you only what to know if the variable is a number, regardless of whether it's actually an int, a float or a string, use is_numeric.
If you need it to have a non-zero decimal part, you can do:
//if we already know $number is numeric...
if ((int) $number == $number) {
//is an integer
}
The is_numeric() function checks whether a variable is a number or a numeric string. This function returns true if the variable is a number or a numeric string, otherwise it returns false/nothing.
$number = 0.5;
echo is_numeric($number); //true
OR
$number = "0.5";
echo is_numeric($number); //true
Read more in:
Artefacto's answer will also convert a 5.0 float number into a 5 integer. If that is bugging you like it was bugging me, I offer the answer of automatic type conversion via the multiplication operator:
If either operand is a float, then both operands are evaluated as floats, and the result will be a float. Otherwise, the operands will be interpreted as ints, and the result will also be an int.
$demo = array(
1, 2, 3, '1', '2', '3',
1.0, 2.1, 3.2, '1.0', '2.1', '3.2',
-17, '-17',
-1.0, -2.2, '-1.0', '-2.2',
0, '0', -0, '-0',
0.0, '0.0', -0.0, '-0.0',
);
foreach ($demo as $k => $v) {
if (is_numeric($v) && is_string($v)) {
$demo[$k] = 1 * $v;
}
}
echo "<pre>"; var_dump($demo); echo "</pre>";
array(26) {
[0]=>
int(1)
[1]=>
int(2)
[2]=>
int(3)
[3]=>
int(1)
[4]=>
int(2)
[5]=>
int(3)
[6]=>
float(1)
[7]=>
float(2.1)
[8]=>
float(3.2)
[9]=>
float(1)
[10]=>
float(2.1)
[11]=>
float(3.2)
[12]=>
int(-17)
[13]=>
int(-17)
[14]=>
float(-1)
[15]=>
float(-2.2)
[16]=>
float(-1)
[17]=>
float(-2.2)
[18]=>
int(0)
[19]=>
int(0)
[20]=>
int(0)
[21]=>
int(0)
[22]=>
float(0)
[23]=>
float(0)
[24]=>
float(-0)
[25]=>
float(-0)
}