PHP Booleans
A boolean represents one of two possible values: true or false.
Booleans are the simplest data type. They hold only true or false and are used constantly in conditional testing.
Truthy and falsy
When a non-boolean value is used in a boolean context, PHP converts it. The following are treated as false: 0, 0.0, "", "0", an empty array, and NULL. Almost everything else is true.
Example
Loading editor…
Press Run to execute the code.
When to use it
- Toggle a user's account active flag in a database with a boolean column.
- Gate access to an admin panel by checking a $isAdmin boolean returned from a session.
- Use the boolean return value of file_put_contents() to detect write failures.
More examples
Boolean literals in conditions
Boolean variables keep condition expressions readable and avoid magic numbers like 1/0 in logic checks.
<?php
$isLoggedIn = true;
$isBanned = false;
if ($isLoggedIn && !$isBanned) {
echo "Welcome back!";
}Truthy and falsy values
PHP casts many values to boolean implicitly; knowing which are falsy prevents subtle if-statement bugs.
<?php
var_dump((bool) 0); // false
var_dump((bool) ""); // false
var_dump((bool) []); // false
var_dump((bool) null); // false
var_dump((bool) 1); // true
var_dump((bool) "hi"); // trueStrict boolean comparison
Using !== false avoids the falsy-zero trap when a function can legitimately return position 0.
<?php
$result = strpos("hello world", "world");
if ($result !== false) {
echo "Found at position: $result";
}
Discussion