I try to execute this code
<?php
$id = 'p1';
echo $id."<br>";
echo ($id == 0) ? 'true' : 'false';
?>
Can anyone explain to me why PHP considers 'p1' equals 0?
I try to execute this code
<?php
$id = 'p1';
echo $id."<br>";
echo ($id == 0) ? 'true' : 'false';
?>
Can anyone explain to me why PHP considers 'p1' equals 0?
Php does implicit conversion from string 'p1'
to number int(0)
when comparing string with number:
var_dump((int)'p1');
// int(0)
So what's really happening is:
echo ((int)'p1') == 0) ? 'true' : 'false';
So any string not beginning with a number compared with zero will result into true
, therefore you get 'true'
in your script.
From the documentation
When converting to boolean, the following values are considered FALSE:
the boolean FALSE itself the integer 0 (zero) the float 0.0 (zero) the empty string, and the string "0" an array with zero elements an object with zero member variables (PHP 4 only) the special type NULL (including unset variables) SimpleXML objects created from empty tags
Every other value is considered TRUE (including any resource).
Your string isn't empty, thus it is TRUE
From the PHP Manual:
If we try to compare a number with a string or the comparison involves numerical strings, then each string is converted to a number and the comparison performed numerically
As you can see in the Comparison Operators table on the same page:
$a === $b
-- Identical --TRUE
if$a
is equal to$b
, and they are of the same type.
This is due to the fact that php is loosely typed language.
Basically comparison between different types ( string and an integer in your case ) sometimes has surprising results. And it's basically never advised to compare variables of different type. Nevertheless you can use the [Type Comparison Tables] (click) 1 to check what results to expect and to find which cases won't have surprising outcomes.