Coalesce Function For PHP?
Answer :
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
.
First hit for "php coalesce" on google.
function coalesce() { $args = func_get_args(); foreach ($args as $arg) { if (!empty($arg)) { return $arg; } } return NULL; }
http://drupial.com/content/php-coalesce
Comments
Post a Comment