Php - Boolean

Card Puncher Data Processing

About

This page is about the boolean data type in Php.

Because of this dynamic nature, php has a weak typing. It considers then a lot of different value as true or false and it can get really confusing. This article shows the main aspect of the php boolean to be able to survive its different behaviors.

Management

Assignment

  • Boolean non-sensitive constant (True and False)
$foo = True;

Conversion

Explicit

  • Text Boolean
// the empty string, and the string "0" are false
(bool)('') = false;
(bool)('Some text') = true;
  • Number Boolean
// the integer 0 (zero) and the float 0.0 (zero)  are false
(bool)(0) = false;
(bool)(-1) = true;
(bool)(1) = true;
(bool)(2) = true;

The following element are considered as false (other cases are true)

  • 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

From String

PHP - String

filter_var(    'true', FILTER_VALIDATE_BOOLEAN); // true
filter_var(         1, FILTER_VALIDATE_BOOLEAN); // true
filter_var(       '1', FILTER_VALIDATE_BOOLEAN); // true
filter_var(      'on', FILTER_VALIDATE_BOOLEAN); // true
filter_var(     'yes', FILTER_VALIDATE_BOOLEAN); // true

filter_var(   'false', FILTER_VALIDATE_BOOLEAN); // false
filter_var(         0, FILTER_VALIDATE_BOOLEAN); // false
filter_var(       '0', FILTER_VALIDATE_BOOLEAN); // false
filter_var(     'off', FILTER_VALIDATE_BOOLEAN); // false
filter_var(      'no', FILTER_VALIDATE_BOOLEAN); // false
filter_var('nonemptystring', FILTER_VALIDATE_BOOLEAN); // false
filter_var(        '', FILTER_VALIDATE_BOOLEAN); // false
filter_var(      null, FILTER_VALIDATE_BOOLEAN); // false

To String

var_export($myBoolean, true);

Documentation / Reference





Discover More
Card Puncher Data Processing
Php - Logical Operator

See logical operator boolean operatorsalways return a boolean value. It doesn't return the value of the last evaluated expression.



Share this page:
Follow us:
Task Runner