Consider the following PHP code:
$a = 0.1 + 0.2; echo $a === 0.3 ? 'Equal' : 'Not equal';
What will be printed?
$a = 0.1 + 0.2; echo $a === 0.3 ? 'Equal' : 'Not equal';
Think about how floating point numbers are stored in computers.
Due to floating point precision, 0.1 + 0.2 is not exactly 0.3 in PHP, so the strict comparison fails and 'Not equal' is printed.
What does this PHP code output?
$num = 1.23456789; echo number_format($num, 4);
$num = 1.23456789; echo number_format($num, 4);
number_format rounds the number to the specified decimals.
number_format rounds the number to 4 decimal places, so 1.23456789 becomes 1.2346.
Examine this PHP code snippet:
$x = 0.15 + 0.15;
$y = 0.1 + 0.2;
if ($x == $y) {
echo 'Equal';
} else {
echo 'Not equal';
}Why does it print 'Not equal'?
$x = 0.15 + 0.15; $y = 0.1 + 0.2; if ($x == $y) { echo 'Equal'; } else { echo 'Not equal'; }
Try printing the values of $x and $y with high precision.
0.15 + 0.15 equals exactly 0.3 in floating point, but 0.1 + 0.2 does not due to precision errors, so the comparison fails.
Which of the following PHP code snippets will cause a syntax error?
Look carefully at the float literal formats.
Option C has two decimal points in the number literal, which is invalid syntax in PHP.
What is the number of elements in this PHP array?
$arr = []; $arr[1.0] = 'a'; $arr[1.00] = 'b'; $arr[1.000] = 'c'; echo count($arr);
$arr = []; $arr[1.0] = 'a'; $arr[1.00] = 'b'; $arr[1.000] = 'c'; echo count($arr);
Think about how PHP treats float keys in arrays.
PHP converts float keys to integers when used as array keys, so all keys become 1, overwriting previous values. The array has 1 element.