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?
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?
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';
First hit for "php coalesce" on google.
function coalesce() {
$args = func_get_args();
foreach ($args as $arg) {
if (!empty($arg)) {
return $arg;
}
}
return NULL;
}
I really like the ?: operator. Unfortunately, it is not yet implemented on my production environment. So I use the equivalent of this:
function coalesce() {
return array_shift(array_filter(func_get_args()));
}
Make sure you identify exactly how you want this function to work with certain types. PHP has a wide variety of type-checking or similar functions, so make sure you know how they work. This is an example comparison of is_null() and empty()
$testData = array(
'FALSE' => FALSE
,'0' => 0
,'"0"' => "0"
,'NULL' => NULL
,'array()'=> array()
,'new stdClass()' => new stdClass()
,'$undef' => $undef
);
foreach ( $testData as $key => $var )
{
echo "$key " . (( empty( $var ) ) ? 'is' : 'is not') . " empty<br>";
echo "$key " . (( is_null( $var ) ) ? 'is' : 'is not') . " null<br>";
echo '<hr>';
}
As you can see, empty() returns true for all of these, but is_null() only does so for 2 of them.
I'm currently using this, but I wonder if it couldn't be improved with some of the new features in PHP 5.
function coalesce() {
$args = func_get_args();
foreach ($args as $arg) {
if (!empty($arg)) {
return $arg;
}
}
return $args[0];
}
A function to return the first non-NULL value:
function coalesce(&...$args) { // ... as of PHP 5.6
foreach ($args as $arg) {
if (isset($arg)) return $arg;
}
}
Equivalent to $var1 ?? $var2 ?? null in PHP 7+.
A function to return the first non-empty value:
function coalesce(&...$args) {
foreach ($args as $arg) {
if (!empty($arg)) return $arg;
}
}
Equivalent to (isset($var1) ? $var1 : null) ?: (isset($var2) ? $var2 : null) ?: null in PHP 5.3+.
The above will consider a numerical string of "0.00" as non-empty. Typically coming from a HTTP GET, HTTP POST, browser cookie or the MySQL driver passing a float or decimal as numerical string.
A function to return the first variable that is not undefined, null, (bool)false, (int)0, (float)0.00, (string)"", (string)"0", (string)"0.00", (array)[]:
function coalesce(&...$args) {
foreach ($args as $arg) {
if (!empty($arg) && (!is_numeric($arg) || (float)$arg!= 0)) return $arg;
}
}
To be used like:
$myvar = coalesce($var1, $var2, $var3, ...);