I have a PHP array like so:
$booleans = array(true, '||', false, '&&', true, '||', false);
Now I would now like to convert this array to a condition, e.g.:
if(true || false && true || false){
// Do something
}
else{
// Do something else
}
Preferably, for security reasons, I want to avoid using eval
.
Is this possible? If so, what is the most efficient way to do it?
This is not a finite solution for all operations and precedence, but a direction on how you may resolve it. You can refer to Shunting yard algorithm .
$validateExpression = function (array $expression): bool {
$allowedOperators = ['&&', '||'];
$values = [];
$operators = [];
foreach ($expression as $expr) {
if (is_bool($expr)) {
$values[] = $expr;
continue;
}
if (in_array($expr, $allowedOperators)) {
$operators[] = $expr;
continue;
}
throw new \InvalidArgumentException('Invalid expression');
}
while($operators) {
$a = array_shift($values);
$b = array_shift($operators);
$c = array_shift($values);
array_unshift($values, match($b) {
'&&' => $a && $c,
'||' => $a || $c,
});
}
return reset($values);
};
var_dump($validateExpression([true, '||', false, '&&', true, '||', false]));
var_dump(true || false && true || false);
bool(true)
bool(true)