PHP modulo foreach条件只显示偶数个数组

时间:2014-09-05 10:37:02

标签: php arrays modulo

我是PHP的新手,并且在其中学习了一个类,我有一个仅从数组中返回偶数的赋值。从php.net网站模数应该适用于此,但它似乎没有返回任何东西。这段代码有什么问题?

<?php
        // colors Array
        $colors = array(
            0 => "Red",
            1 => "Pink",
            2 => "Blue",
            3 => "Baby Blue",
            4 => "Green",
            5 => "Lime",
            6 => "Black",
            7 => "Grey",
            8 => "Purple",
            9 => "Violet"
        );

        // Repeat Part 1 above, but only display the solid colors
        krsort($colors);
        // For Each item in array, Loop through the colors of the array and display the index number and color name.
        foreach($colors as $key => $color){
            if($key % == 2)
                echo "<p class='sub-heading'>Color: {$key}: is {$color}</p>";

        } // end forEach loop
        ?>

1 个答案:

答案 0 :(得分:2)

使用模运算符获得所需结果的正确方法:$key % 2 === 0

所以,for循环的例子:

foreach($array as $key => $value){
    if($value % 2 === 0) {
        // ...
    }
}