haitruonginfotech haitruonginfotech - 3 months ago 21
PHP Question

Error when use eval in php

I have a sample code:

$messages = array(
array("mark" => "0 < {m} < 4.9", "message" => "BAD"),
array("mark" => "5 < {m} < 10", "message" => "GOOD"),
);
$m = 3;
$message = "";
foreach ($messages as $row) {
$condition = $row['mark'];
$condition = str_replace('{m}', $m, $condition);
$str = "$result = (bool)".$condition;
eval($str);
if($result) $message = $row['message'];
}
echo $message;


Result is BAD, but it show bug:
Parse error: syntax error, unexpected '='
. How to ideas?

Answer

Check your code, apart of double quotes: the expression 0 < 3 < 4.9 is not a valid condition in PHP, so you should change it:

$messages = array(
    array("mark" => "0 < {m} && {m} < 4.9;", "message" => "BAD"),
    array("mark" => "5 < {m} && {m} < 10;", "message" => "GOOD"),
);
$m = 3;
$message = "";
foreach ($messages as $row) {
    $condition = $row['mark'];
    $condition = str_replace('{m}', $m, $condition);
    $str = '$result = (bool)'.$condition;
    eval($str);
    if($result) $message = $row['message'];
}
echo $message; //output: BAD