Coalesce function for PHP?
There is a new operator in php 5.3 which does this: ?:
// Aecho 'A' ?: 'B';// Becho '' ?: 'B';// Becho false ?: 'B';// Becho null ?: 'B';
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
.
First hit for "php coalesce" on google.
function coalesce() { $args = func_get_args(); foreach ($args as $arg) { if (!empty($arg)) { return $arg; } } return NULL;}