PHP Truthy, Falsey
A falsey value is considered false when encountered in a Boolean context.
A truthy value is considered true when encountered in a Boolean context.
The idea of truthy and falsey values allow comparison between what would otherwise be two incomparable data types in a programming language.
For instance, in PHP you can compare a number to a letter:
if (1 > 'a') {
echo 'truthy';
} else {
echo 'falsey';
}
Type Juggling
Type juggling is the process of converting a value to a comparable data type. This is done before a boolean comparison is made. These rules also apply to comparisons using the switch statement.
In PHP if a number is compared with a string, or both values are numerical strings, then each string is converted to a number and the comparison is performed numerically.
How the “truthitude” of a value is determined for a given type in a given language can be pretty arbitrary.
When PHP converts a data type to a boolean for comparison, the following values are considered FALSE:
- The boolean
FALSE
itself. - The integer
0
(zero). - The float
0.0
(zero). - An 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.
Comparison Operators
Comparison operators allow you to compare two values.
Symbol | Name | Description |
---|---|---|
== |
Equal | Checks if the values are equal after type juggling. |
=== |
Identical | Does a type-dependent check. Using this operator basically nullifies truthy/falsey as the comparison also checks if the data types of the values are identical. |
!= |
Not equal | |
<> |
Not equal | |
!== |
Not identical | |
< |
Less than | |
> |
Greater than | |
<= |
Less than or equal to | |
>= |
Greater than or equal to | |
<=> |
Spaceship | An integer less than, equal to, or greater than zero when $a is less than, equal to, or greater than $b , respectively. Available as of PHP 7. |
Tests
if ($test_var) {
echo 'true';
} else {
echo 'false';
}
# `$test_var` example definitions and results as given by the structure above:
$test_var = ''; // false
$test_var = ""; // false
$test_var = '0'; // false
$test_var = "0"; // false
$test_var = 0; // false
$test_var = 0.0; // false
$test_var = []; // false
$test_var; // false - NOTICE Undefined variable...
(not defined) // false - NOTICE Undefined variable...
$test_var = 1; // true
$test_var = 'a'; // true
$test_var = "a"; // true
$test_var = a; // true - NOTICE Use of undefined constant a...