Logical
All logical operators only work with Boolean values.
/**
* AND && True if BOTH operands evaluate to true
* OR || Evaluates to true if EITHER operands true
* XOR Evaluates to true if either operands true, but NOT BOTH
*
* PHP will first convert any other value to a Boolean ...
* and then perform the operation
*/
$a = 1; $a2 = null; $a3 = 'NULL';
var_dump(isset($a) && isset($a2)); // false
var_dump(isset($a) && isset($a3)); // true
var_dump(isset($a) || isset($a2)); // true
var_dump(isset($a) || isset($a3)); // true
$a = "1"; $b = "abc";
var_dump(is_numeric($a) XOR is_numeric($b)); // true
var_dump($a && $b); // true, automatic convertion to Boolean
Shorthands
There are a couple less known operators.
/**
* Ternary
*
* x = expr1 ? expr2 : expr3
* x = expr2 if expr1 = TRUE
*
* Ternary shorthand
*
* x = expr1 ?: expr3
* x = expr1 if expr1 = TRUE
*
* Null coalescing
*
* x = expr1 ?? expr2
* x = expr1 if expr1 exists and not null
*/
$a = 1;
$b = 1;
var_dump($a == $b ? "true" : "false"); // true
var_dump($a ?: $b); // 1
var_dump($n ?? "None"); // None
Last update: 382 days ago