Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does true/false work in PHP?

Tags:

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 ?

like image 980
Moon Avatar asked Mar 04 '10 20:03

Moon


People also ask

What is true and false in PHP?

A boolean value represents a truth value, which is either true or false . PHP evaluates the following values to false: false, 0, 0.0, empty string (“”), “0”, NULL, an empty array; other values are true .

How do you check if a variable is true or false in PHP?

The is_bool() function checks whether a variable is a boolean or not. This function returns true (1) if the variable is a boolean, otherwise it returns false/nothing.

Does PHP have boolean?

Definition and Usage This is one of the scalar data types in PHP. A boolean data can be either TRUE or FALSE. These are predefined constants in PHP. The variable becomes a boolean variable when either TRUE or FALSE is assigned.

What is false PHP?

When converting to boolean, the following values are considered FALSE: the boolean FALSE itself. the integer 0 (zero) the float 0.0 (zero)


1 Answers

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.

like image 80
Mark Byers Avatar answered Sep 22 '22 18:09

Mark Byers