Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to assign first non false variable from a group of them

I tried this way without effect:

$a = false;
$b = false;
$c = 'sometext';
$result = $a or $b or $c or exit('error: all variables are false');

and $result should be set to $c, but this gives value of bool(false) instead.

like image 240
rsk82 Avatar asked Jul 02 '11 14:07

rsk82


2 Answers

What about:

$result = $a ?: $b ?: $c ?: exit('doh!');
like image 126
Matt Avatar answered Nov 12 '22 20:11

Matt


($result = $a) || ($result = $b) || ($result = $c) || exit("no");

or if you want 0 and empty string etc. not count as false:

(($result = $a) !== false) || (($result = $b) !== false) || (($result = $c) !== false) || exit("no");

think about whether this is really readable. You could also use the old fashioned way:

if ($a !== false)
  $result = $a;
elseif ($b !== false)
  $result = $b;
elseif ($c !== false)
  $result = $c;
else
  exit("no");

Edit: Just in case you ever need something dynamic ;-).

foreach(array('a','b','c') as $key)
  if (($result = $$key) !== false)
    break;
if ($result === false)
  exit("no");
like image 43
yankee Avatar answered Nov 12 '22 20:11

yankee