将字符串计算为条件表达式

时间:2014-05-03 12:20:12

标签: php eval

我的表达式如下:

$condition = "$foo>$bar";

和一个包含表达式元素值的数组:

    array(
     'foo' => 3,
     'bar' => 4
    )

我使用$condition函数在str_replace()字符串中进行了替换,但3>4表达式返回true。

如何在$condition声明中正确评估我的if()表达式?

2 个答案:

答案 0 :(得分:1)

我不知道您为什么要这样做,但这在技术上是可行的。使用extract()将数组中的变量导入当前范围。获得变量后,您可以像往常一样对它们进行比较:

$values =array(
     'foo' => 3,
     'bar' => 4
);

extract($values);

$result = $foo > $bar;

if ($result) {
    echo '$foo is greater than $bar';
} else {
    echo '$foo is not greater than $bar';
}

如果$condition是字符串而您无法更改,则可以先使用eval()来评估表达式:

$condition = "$foo>$bar";
eval(sprintf('$result = %s;', $condition));

if ($result) {
    echo '$foo is greater than $bar';
} else {
    echo '$foo is not greater than $bar';
}

答案 1 :(得分:0)

如果值“too”“bar”在数组中并且可以是字符串或整数,那么为什么不使用数组排序函数来评估这种方式:

<?php

$values =array(
     'foo' => 'mary and john',
     'bar' => 'john and mary'
);


/**
 * This sorts the arrays by ascending order * 
 * Result: Array ( [bar] => 2 [foo] => 5 ) * 
 */ 
natsort($values);


/**
 * now run the condition 
 * To do this we check the first key, which naturally is the smallest key
 * Alternatively, we could also check the last key, the higher value
 */
$keys=array_keys($values);


$lower_key=reset($keys);
$higher_value=end($keys);

if($lower_key=='foo'){
    echo 'Foo <strong>('.$values['foo'].')</strong> is less tha Bar <strong>('.$values['bar'].')</strong>';
}
else{
    echo 'Foo <strong>('.$values['foo'].')</strong> is greater than Bar <strong>('.$values['bar'].')</strong>';
}

/**
 * This can be summarized as
 */
natsort($values);

if(reset(array_keys($values))=='foo'){
    echo 'Foo <strong>('.$values['foo'].')</strong> is less tha Bar <strong>('.$values['bar'].')</strong>';
}
else{
    echo 'Foo <strong>('.$values['foo'].')</strong> is greater than Bar <strong>('.$values['bar'].')</strong>';
}    


//Foo (mary and john) is greater than Bar (john and mary)

?>