Reputation: 9
I have one variable which contains the condition dynamically and I need to check that condition. For example,
$condition = '21 < 20';
if($condition){
echo "yes";
} else {
echo "no";
}
I want to check this condition but it always returns "yes" because the condition variable has some string. How can I actually check the condition that 21 is greater than 20. Can anyone pass through this kind of problem? Thanks.
Upvotes: 0
Views: 1237
Reputation: 307
Straight from PHP.net
Caution The eval() language construct is very dangerous because it allows execution of arbitrary PHP code. Its use thus is discouraged. If you have carefully verified that there is no other option than to use this construct, pay special attention not to pass any user provided data into it without properly validating it beforehand.
With that said, using your requirements (and part of your code), your result will look something like this:
// Define the condition from the other function
$condition = '5>3';
// Grab the result of evaluating that condition
// VERY DANGEROUS IF YOU CANNOT TRUST THE INPUT
$result = eval('return ('.$condition.');');
// Execute a normal if statement check
if($result){ echo "yes";} else {echo "no";}
Upvotes: 1