I’m facing a weird issue with PHP. This simple example:
<?php
$array = array(
'zero',
'one',
'id' => 'two'
);
foreach ($array as $key => $value) {
if ($key == "id") {
echo "Key: ". $key .", value: ". $value ."\n";
}
}
?>
should (imho) output this:
Key: id, value: two
But it outputs
Key: 0, value: zero
Key: id, value: two
How is this possible: 0 == "id"?
When $key is
0and gets compared to the string “id“, the string (“id“) will be converted to an integer. Since “id” can’t be turned into a valid integer that conversion will yield0, and the if statement becomes true.Since you don’t want the implicit conversion to happen between two types who aren’t compatible use the more strict
===version of==.===will see if the variables are of the same type and has the same exact value.Documentation PHP: Comparison Operators
Examples
output