Reputation: 81
I must use those strings to do the condition. Because of the $op is string, so it cannot run the condition correctly. Please help.
<?php
//$op = $condition[$i]. " " .$operant[$i]. " " .$participant_index;
$op = "1 == 5";
if($type[$i]=="person" && $op){
echo "ok";
}
?>
Upvotes: 0
Views: 246
Reputation: 683
Try this code:
<?php
//$op = $condition[$i]. " " .$operant[$i]. " " .$participant_index;
$op = "1 == 5";
if($type[$i]=="person" && eval("return $op;"))
{
echo "ok";
}
?>
Upvotes: 0
Reputation: 3362
If you can guarantee that the value of $op
isn't evil, then use eval
:
if ($type[$i]=="person" && eval("return ".$op){
echo "ok";
}
Be carefull with this, as it will parse the content of $op
as PHP code.
Upvotes: 1
Reputation: 522081
You need to evaluate that string as code, PHP won't do that implicitly for you.
eval()
can do that, but since eval
will freely execute any and all code you give it using full PHP permissions, this is a giant security risk, depending on where those strings come from.
The better solution is to use a limited expression engine which parses and evaluates the string, being able to only handle a few select expressions. You could write something like this yourself, but the difficulty of that greatly depends on what expressions you may possibly allow. The Symfony framework offers a decent ExpressionLanguage
component which can already do just that.
Upvotes: 2
Reputation: 41837
The easy (but potentially harmful) way:
$op = "1 == 5";
if (eval("return " . $op . ";")) {
// do your thing.
}
Upvotes: 0