How to assign the 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 instead it gives a value bool(false).

+5
source share
4 answers

Several things happen here:

First, in PHP, the result of a boolean operation is logical.

Secondly, and more subtly, "English" Boolean operators ( orand and) have the lowest precedence - below the assignment operator =.

$result $a ( $a), .

// This has the same effect:
$result = $a or $b or $c;

// As this:
$result = $a;
$a or $b or $c; // this has no effect

, .

, - $a, $b, $c (.. true true), "C-" (|| &&), :

// These all have the same effect:

$result = ($a or $b or $c);
$result = $a || $b || $c;

if ($a or $b or $c)
  $result = true;
else
  $result = false;

if ($a || $b || $c)
  $result = true;
else
  $result = false;

, - , , , .

(, ), .

, ( , , ) array_filter - all , , .

:

$a = false;
$b = false;
$c = 'sometext';
$result = array_filter(array($a, $b, $c));

var_dump($result);

:

array(1) {
  [2]=>
  string(8) "sometext"
}
+1

:

$result = $a ?: $b ?: $c ?: exit('doh!');
+7
($result = $a) || ($result = $b) || ($result = $c) || exit("no");

0 .., false:

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

, . :

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

Edit: just in case, you need something dynamic; -).

foreach(array('a','b','c') as $key)
  if (($result = $$key) !== false)
    break;
if ($result === false)
  exit("no");
+4
source

The result of a boolean boolean operator in php.

$a = false;
$b = false;
$c = 'sometext';
$result = null;

foreach(array('a', 'b', 'c') as $k)
{
    if($$k !== false)
    {
        $result = $$k;
        break;
    }
}

Also, consider moving variables to an array.

+2
source

All Articles