Sunny Luthra Sunny Luthra - 4 months ago 13
PHP Question

Converting Boolean values inside array into if statement

What is the best way to convert array values in to if statement. The array values should be compared by AND and the arrays by OR. I can do this using EVAL but looking for something other than EVAL.

$arr = Array(
[0] => Array
(
[0] => false
[1] => true
)
[1] => Array
(
[0] => true
[1] => false
)
[2] => Array
(
[0] => false
)
[3] => Array
(
[0] => true
)
[4] => Array
(
[0] => true,
[1] => true,
[2] => true
)
)


I want to build comparison dynamically for if statement..

For example

if( ($arr[0][0] && $arr[0][1]) || ($arr[1][0] && $arr[1][1]) .... and so on )

Answer
$result = array_reduce($arr, function ($result, array $values) {
    return $result || array_reduce($values, function ($result, $value) {
        return $result && $value;
    }, true);
}, false);

if ($result) ...

One array_reduce can elegantly do this for one array, you simply want to do it for two nested array levels.

Comments