1

The PHP 5.6 code:

$nl = '<br/>';
$text = 'hello';
$res = $text? 'true': 'false';
echo "$text evaluates to $res $nl";

$num = 0;
$res = $num? 'true': 'false';
echo "0 evaluates to $res $nl";

$res = $text == 0? 'true': 'false';
echo "$text == $num evaluates to $res $nl";

This outputs:

hello evaluates to true
0 evaluates to false
hello == 0 evaluates to true

I don't understand the last line of output. How can something true be compared to something false and have a comparison result of true?

Answer: The string and the integer are not both converted to booleans as I suspected. Instead, the string is converted to a number and then compared to 0. Because the string does not begin with a numeric character, it evaluates to the number 0 (var_dump((int)'hello') will output int 0). So the comparison returns true because "hello" == 0 becomes 0 == 0

BeetleJuice
  • 39,516
  • 19
  • 105
  • 165

0 Answers0