Many programming languages have a coalesce function (returns the first non-NULL value, example). PHP, sadly in 2009, does not.
What would be a good way to implement one in PHP until PHP itself gets a coalesce function?
Null coalescing operator ¶ The null coalescing operator ( ?? ) has been added as syntactic sugar for the common case of needing to use a ternary in conjunction with isset(). It returns its first operand if it exists and is not null ; otherwise it returns its second operand.
The MySQL COALESCE() function is used for returning the first non-null value in a list of expressions. If all the values in the list evaluate to NULL, then the COALESCE() function returns NULL. The COALESCE() function accepts one parameter which is the list which can contain various values.
Uses of Null Coalescing Operator: It is used to replace the ternary operator in conjunction with the PHP isset() function. It can be used to write shorter expressions. It reduces the complexity of the program. It does not throw any error even if the first operand does not exist.
In PHP, a variable with no value is said to be of null data type. Such a variable has a value defined as NULL. A variable can be explicitly assigned NULL or its value been set to null by using unset() function.
There is a new operator in php 5.3 which does this: ?:
// A echo 'A' ?: 'B'; // B echo '' ?: 'B'; // B echo false ?: 'B'; // B echo null ?: 'B';
Source: http://www.php.net/ChangeLog-5.php#5.3.0
PHP 7 introduced a real coalesce operator:
echo $_GET['doesNotExist'] ?? 'fallback'; // prints 'fallback'
If the value before the ??
does not exists or is null
the value after the ??
is taken.
The improvement over the mentioned ?:
operator is, that the ??
also handles undefined variables without throwing an E_NOTICE
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With