-2

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?

4 Answers4

3

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.

Vyktor
  • 20,559
  • 6
  • 64
  • 96
1

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

Andy
  • 49,085
  • 60
  • 166
  • 233
  • 1
    That would apply if the test was `if ($p1)...`. The OP specifically compared the string to a numeric 0, so a conversion to integer was done first. – Phil Perry Feb 07 '14 at 14:12
1

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.

Amal Murali
  • 75,622
  • 18
  • 128
  • 150
Ferrakkem Bhuiyan
  • 2,741
  • 2
  • 22
  • 38
1

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.

Jordan Parker
  • 239
  • 3
  • 8