Reputation: 53
I have the following code:
<?php
$val = 0;
$res = $val == 'true';
var_dump($res);
?>
I always was under impression that $res should be 'false' as in the above expression PHP would try to type cast $val to boolean type (where zero will be converted as false) and a string (non-empty string is true). But if I execute the code above output will be:
boolean true
Am I missing something? Thanks.
Upvotes: 2
Views: 804
Reputation: 270775
In PHP, all non-empty, non-numeric strings evaluate to zero, so 0 == 'true'
is TRUE, but 0 === 'true'
is FALSE. The string true
has not been cast to a boolean value, but is being compared as a string to the zero. The zero is left as an int value, rather than cast as a boolean. So ultimately you get:
// string 'true' casts to int 0
0 == 0 // true
Try this:
echo intval('true');
// 0
echo intval('some arbitrary non-numeric string');
// 0
Review the PHP type comparisons table. In general, when doing boolean comparisons in PHP and types are not the same (int to string in this case), it is valuable to use strict comparisons.
Upvotes: 3
Reputation: 2102
Try this
<?php
$val = 1;
$res = (bool)$val == 'true';
var_dump($res);
?>
Upvotes: 0
Reputation: 219924
Because $val
is the first operator PHP converts the string true
to an integer which becomes 0. As a result 0 ==0 and your result is true;
Upvotes: 0