An Integer is Not an Integer

Another day, another unexpected behaviour encountered in  wonderland. Funny that a number returned from a function that looks like an integer is actually not an integer. Let's illustrate this with a simple example.

1. Start the interactive mode.
$ php -a

2. Let's find the square root of number 9, using sqrt function.
php > echo sqrt(9), "\n";

3. Obviously 3 is an integer right? Just to confirm, let's use is_int function to check it. Nope, is not.
php > echo is_int(sqrt(9)), "\n";

4. Checking the sqrt function documentation again. It seemed that sqrt will return float data type even though the decimal point is not shown. Let's try with is_float or gettype function.
php > echo is_float(sqrt(9)), "\n";
php > echo gettype(sqrt(9)), "\n";

Double ? Isn't it supposed to return float ? According to documentation [4], double was used instead of float due to historical reason. Why ? No effing idea what so ever.

5. Still, how we going to check for integer, is this case, to find out which number is the perfect square (an integer is a square of another integer) ? Type casting. See example below.
php > $root = sqrt(9); echo $root == (int)$root, "\n";

Another day, another gotcha in PHP world.

No comments:

Post a Comment