0

Possible Duplicate:
Coalesce function for PHP?

I'm not sure what this is normally called, but I hope the title communicates well enough. What I have is a handful of variables some of which might be null.

I want to do:

$a = $b || $c || $d;

Where $a ends up being = to the first non-null variable.

Community
  • 1
  • 1
Joren
  • 9,623
  • 19
  • 63
  • 104
  • Are you trying to assign the contents of b OR c OR d to a :\? – theBigChalk Jun 16 '12 at 00:25
  • 2
    Wrong language for this. It would work in Ruby or JavaScript. In PHP, AFAIK, you need to go with the trinary operator and write `$b !== null ? $b : ($c !== null ? $c : $d)` – Amadan Jun 16 '12 at 00:26
  • See also: http://stackoverflow.com/questions/1013493/coalesce-function-for-php – Wrikken Jun 16 '12 at 00:34

3 Answers3

4

To my knowledge, PHP doesn't support this in the same way JavaScript does.

You can, however do something like this:

$a = $b ? $b : ($c ? $c : $d);

A more general solution:

function fallthrough($arr) {
    //$arr should be an array of possible values. The first non-null value is returned
    do $a = array_shift($arr);
    while($a === null && $arr);
    return $a;
}
Niet the Dark Absol
  • 320,036
  • 81
  • 464
  • 592
  • So, what would be the best way to do this in PHP? Clearly I can't just nest ternary operators as that will get insane with more variables. Do I just have a big if elseif block? – Joren Jun 16 '12 at 00:27
  • Careful - if `$b` is `"0"`, it will fall through. To be more precise, it will fall through on any falsy value. If you really need only `null` to fall through, you need to explicitly test. – Amadan Jun 16 '12 at 00:29
  • What you could do is define a function. I'll edit my answer with a solution. – Niet the Dark Absol Jun 16 '12 at 00:30
3
<?php
$a = 0;
$b = false;
$c = true; //should become this
$d = '1';
$e =  $a ?: $b ?: $c ?: $d;
var_dump($e);
//bool(true)

//should be '1' if order is different
$e =  $a ?: $b ?: $d ?: $c;
var_dump($e);
//string(1) "1"

... however ?: is kinda new, you will confuse your colleagues / fellow coders.

Wrikken
  • 69,272
  • 8
  • 97
  • 136
0

I don't think that's possible. I think you'd have to use some other, more laborious, way. I.e. make an array of the variables, iterate through it until you find a non-null value and break the loop, like so:

$vars = array("b" => $b, "c" => $c, "d" => $d);

foreach($vars as $var) {
   if($var != null) {
      $a = $var;
      break;
   }
}

Well, like some other answers here say, you can use the shorthand way of writing this, but writing readable code is important too. The above code is pretty readable.

Joe Dyndale
  • 1,073
  • 1
  • 15
  • 32