Skip to content
Advertisement

How does true/false work in PHP?

I wonder how PHP handles true/false comparison internally.
I understand that true is defined as 1 and false is defined as 0.
When I do if("a"){ echo "true";} it echos “true“. How does PHP recognize “a” as 1 ?

Advertisement

Answer

This is covered in the PHP documentation for booleans and type comparison tables.

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.

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement