140

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.
    – kojiro
    Commented Oct 1, 2014 at 13:42
  • More information about the null coalesce operator can be found here - stackoverflow.com/questions/33666256/…
    – Peter
    Commented Nov 12, 2015 at 11:04
  • 1
    Just to Note, PHP7 Implemented this fucntion
    – Grzegorz
    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 ;)
    – hakre
    Commented Apr 22, 2018 at 11:26
  • By function i did not mean function ;) Feature. I wasn't precise. Thank you :)
    – Grzegorz
    Commented Apr 22, 2018 at 13:07

10 Answers 10

202

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

9
  • 25
    What about multiple ternary shortcuts, would something like "echo $a ?: $b ?: $c ?: $d;" work?
    – ChrisR
    Commented Mar 26, 2010 at 13:55
  • 5
    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'] ?: '?'
    – Benbob
    Commented Jul 12, 2011 at 23:28
  • 5
    You should get an Undefined Index notice irrespective of using the coalesce operator.
    – Kevin
    Commented Jul 13, 2011 at 17:16
  • 2
    Multiple falsey arguments return the last argument, array() ?: null ?: false returns false. The operator is indeed sane.
    – Brad Koch
    Commented Oct 7, 2013 at 13:19
  • 6
    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
    – DanMan
    Commented May 24, 2014 at 11:48
74

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
  • 1
    Finally no more isset() and empty() all over the place! Commented Apr 4, 2016 at 7:06
  • 9
    @timeNomad you will still need is empty, it checks for null only Commented May 19, 2016 at 0:35
  • The only way to get safe "falsy-coalesce" is to use a bit of both: ($_GET['doesNotExist'] ?? null) ?: 'fallback' Commented Jul 18, 2017 at 1:37
  • 1
    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';
    – Matt Borja
    Commented Jan 7, 2020 at 5:13
  • Will it give fatal error if used in libraries that sill support php older versions like 5.5? Commented Jan 16, 2023 at 18:07
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
  • 9
    Save a tiny bit of ram and don't duplicate the args into an array, just do foreach(func_get_args() as $arg) {}
    – TravisO
    Commented Jun 18, 2009 at 20:38
  • 18
    @[Alfred,Ciaran] - you are incorrect. foreach() evaluates the first argument only once, to get an array, and then iterates over it.
    – gahooa
    Commented Dec 12, 2009 at 1:34
  • 6
    Putting func_get_args() inside the foreach (here as $arg) won't change anything from a performance point of view.
    – Savageman
    Commented Dec 12, 2009 at 1:47
  • 7
    @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
    – ChrisR
    Commented Mar 26, 2010 at 13:53
  • 5
    Ironically, this is now the first hit for "php coalesce" on Google. Commented Aug 23, 2014 at 15:52
18

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
  • 1
    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/… Commented Jan 18, 2013 at 21:19
  • 3
    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).
    – Madbreaks
    Commented Feb 20, 2013 at 22:11
  • 1
    Only variables should be passed by reference
    – pronebird
    Commented Aug 16, 2015 at 10:30
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
  • In this case, array unions work pretty nicely ($getstuff = $_GET+$_SESSION+array('id'=>null);$id=$getstuff['id'];).
    – Brilliand
    Commented Dec 29, 2014 at 22:58
  • @Quill what's that supposed to mean? Did you the suggested solution with reference?
    – pronebird
    Commented Aug 16, 2015 at 10:08
  • PHP 7 introduces the lovely new isset ternary operator ?? to make this very common operation more concise.
    – botimer
    Commented Sep 11, 2015 at 20:28
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.

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.

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];
}
0
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
  • Only variables should be passed by reference
    – pronebird
    Commented Aug 16, 2015 at 10:32
  • Yup, I broke the strict rules for the demo, just to make it simple. :) Commented Aug 16, 2015 at 18:27
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, ...);

Not the answer you're looking for? Browse other questions tagged or ask your own question.