141

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?

5
  • 12
    Related: the new null coalescing operator ?? for PHP 7. Commented Oct 1, 2014 at 13:42
  • More information about the null coalesce operator can be found here - stackoverflow.com/questions/33666256/… Commented Nov 12, 2015 at 11:04
  • 1
    Just to Note, PHP7 Implemented this fucntion Commented Dec 30, 2015 at 7:36
  • @Grzegorz: An operator is not a function, or where did you find that function new in PHP 7 ;) Commented Apr 22, 2018 at 11:26
  • By function i did not mean function ;) Feature. I wasn't precise. Thank you :) Commented Apr 22, 2018 at 13:07

10 Answers 10

204

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

Sign up to request clarification or add additional context in comments.

9 Comments

What about multiple ternary shortcuts, would something like "echo $a ?: $b ?: $c ?: $d;" work?
Does not work as expected for arrays. For example when trying to check if an undefined array element is falsey will result in an error.$input['properties']['range_low'] ?: '?'
You should get an Undefined Index notice irrespective of using the coalesce operator.
Multiple falsey arguments return the last argument, array() ?: null ?: false returns false. The operator is indeed sane.
Keep in mind that this doesn't just accept non-null like coalesce in other languages, but any value, which will be implicitly converted to a boolean. So make sure you brush up on your type casting rules
|
75

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.

5 Comments

Finally no more isset() and empty() all over the place!
@timeNomad you will still need is empty, it checks for null only
The only way to get safe "falsy-coalesce" is to use a bit of both: ($_GET['doesNotExist'] ?? null) ?: 'fallback'
The advantage of ?: over ??, however, is that it coalesces empty values as well which ?? does not do. Similar to the behavior of the logical OR operator in JavaScript (i.e. $val || 'default'), I would find ?: to be a more practical form of coalescing if in our practice we ultimately find ourselves handling both empty and null in the same way (i.e. $val ?: 'default'). And if you want to force the issue further and swallow E_NOTICE, you could argue this even: echo @$val ?: 'default';
Will it give fatal error if used in libraries that sill support php older versions like 5.5?
30

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

9 Comments

Save a tiny bit of ram and don't duplicate the args into an array, just do foreach(func_get_args() as $arg) {}
@[Alfred,Ciaran] - you are incorrect. foreach() evaluates the first argument only once, to get an array, and then iterates over it.
Putting func_get_args() inside the foreach (here as $arg) won't change anything from a performance point of view.
@Savageman ... exactly ... if you are thinking of squeezing this millisecond of performance or few bytes of memory out of your application you're probably looking at the wrong performance/memory bottleneck
Ironically, this is now the first hit for "php coalesce" on Google.
|
19

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())); } 

3 Comments

this is a 'truthy' coalesce, using array_filter to get rid of anything that evaluates to false (including null) in the n arguments passed in. My guess is using shift instead of the first element in the array is somehow more robust, but that part I don't know. see: php.net/manual/en/…
I like it but have to agree with @hakre - coalesce is supposed to return the first non-null argument it encounters, which would include FALSE. This function will discard FALSE though, probably not what op has in mind (at least not what I'd want out of a coalesce function).
Only variables should be passed by reference
10

It is worth noting that due to PHP's treatment of uninitalised variables and array indices, any kind of coalesce function is of limited use. I would love to be able to do this:

$id = coalesce($_GET['id'], $_SESSION['id'], null); 

But this will, in most cases, cause PHP to error with an E_NOTICE. The only safe way to test the existence of a variable before using it is to use it directly in empty() or isset(). The ternary operator suggested by Kevin is the best option if you know that all the options in your coalesce are known to be initialised.

3 Comments

In this case, array unions work pretty nicely ($getstuff = $_GET+$_SESSION+array('id'=>null);$id=$getstuff['id'];).
@Quill what's that supposed to mean? Did you the suggested solution with reference?
PHP 7 introduces the lovely new isset ternary operator ?? to make this very common operation more concise.
6

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.

Comments

2

I'm expanding on the answer posted by Ethan Kent. That answer will discard non-null arguments that evaluate to false due to the inner workings of array_filter, which isn't what a coalesce function typically does. For example:

echo 42 === coalesce(null, 0, 42) ? 'Oops' : 'Hooray'; 

Oops

To overcome this, a second argument and function definition are required. The callable function is responsible for telling array_filter whether or not to add the current array value to the result array:

// "callable" function not_null($i){ return !is_null($i); // strictly non-null, 'isset' possibly not as much } function coalesce(){ // pass callable to array_filter return array_shift(array_filter(func_get_args(), 'not_null')); } 

It would be nice if you could simply pass isset or 'isset' as the 2nd argument to array_filter, but no such luck.

Comments

0

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]; } 

Comments

0

PHP 5.3+, with closures:

function coalesce() { return array_shift(array_filter(func_get_args(), function ($value) { return !is_null($value); })); } 

Demo: https://eval.in/187365

2 Comments

Only variables should be passed by reference
Yup, I broke the strict rules for the demo, just to make it simple. :)
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, ...); 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.