PHP - 使用运算符比较数组值

时间:2012-04-06 04:04:42

标签: php arrays operators compare

如果我有一个阵列:

$array = array ( [rock] => 40, [pop] => 30, [rap] => 20 ) etc...

我该怎么做:

foreach key in $array 
{
if (array_value > 30) echo "> 30:" . $array_key . "<br>";
if (array_value < 30) echo "< 30:" . $array_key . "<br>";
}

结果将是:

> 30:rock<br>
< 30:pop<br>
< 30:rap<br>

谢谢!我希望这是有道理的......

2 个答案:

答案 0 :(得分:2)

foreach ($array as $key => $value) {
    if      ($value ...) echo $key...
    else if ($value ...) echo $key...
    ...
}

答案 1 :(得分:2)

deceze的答案一般是正确的,但更具体地说,以下代码应该有效:

foreach ($array as $key => $value) {
    if ($value > 30) {
        echo '> 30:' . $key . '<br>';
    } elseif ($value <= 30) { // Changed this to <= to cover the case of $value = 30
        echo '< 30:' . $key . '<br>';
    }
}