Php - Boolean

1 - 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.

3 - Management

3.1 - Assignment

  • Boolean non-sensitive constant (True and False)

$foo = True;

3.2 - Conversion

3.2.1 - 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

3.2.2 - 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

3.2.3 - To String


var_export($myBoolean, true);

4 - Documentation / Reference


Data Science
Data Analysis
Statistics
Data Science
Linear Algebra Mathematics
Trigonometry

Powered by ComboStrap