How can the below be possible:
$varnum = 4;
if( $varnum/4 - floor($varnum/4) !== 0){
echo 'foo';
}
This echoes ‘foo’ on my server running PHP 5.1.6. If i change the operator to == I get the same results.
I have no idea why, but could it possibly be because “==” is “equals” and “!==” is “Not identical”? How then would I make them identical? I guess in javaScript I would “parseInt”, but there is no such thing in PHP, right?
The reason this fails is because in PHP, the
floorfunction returns afloat, despite the fact that the value is always a whole number. You can see this in the documentation here: http://php.net/manual/en/function.floor.phpYou’re doing a fixed type comparison of that float to an integer zero, so the result is false, regardless of whether the value is actually zero.
To fix this, either:
floorto an integer – eitherintval(float(...))or(int)float(..)!=instead of!==.0.0instead of just0to compare against.In case you’re wondering why
floor()would return a float rather than an integer, it’s because the input is a float. The float data type has a larger possible range than integer, and thus it is possible to callfloor()on a value that would be too big to hold in an integer. Therefore it would not be safe for the function to return an integer; it returns a float instead so that it can guarantee the result will be correct.It may seem odd at first glance, but hopefully that explains the logic behind it for you.