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?
3
Answers
Seems a bit weird to me why you’d want to do that. But for complex repetitive validations you may use functions.
Like so:
Then you can use it in an if statement
I still don’t understand WHY you’d want what you have shown in your question but I think you may be able to accomplish what you want with a similar type of function(s).
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
.
Output
Make sure that array is well-formatted and you can use this code:
First of all collapse all
&&
because they have higher priority, then calculate all||