Display Even Indices in an Array

I’m trying to display only the even Indices of an array, but it’s not working.

Here is my code:

$color = array( "Red", "Pink", "Blue", "Baby Blue", "Green", "Lime", "Gray", "Sunshine");

for ($i = 0; $i < count($color); $i++) {
     if ($color[$i] % 2 === 0) {
        echo "$i is $color";
     }
}

What am I doing wrong?

Answer

Your issue is on line #4 mainly and line #5 partially:

$color = array( "Red", "Pink", "Blue", "Baby Blue", "Green", "Lime", "Gray", "Sunshine");

for ($i = 0; $i < count($color); $i++) {
     if ($i % 2 === 0) { // <- here
        echo "$i is ".$color[$i];
     }
}

You code was essentially equating to:

if ('Red' % 2 === 0) { // with every single color

Since you are using an indexed array, another way of achieving what you need is:

foreach ($color as $k=>$v) {
     if ($k % 2 === 0) {
        echo "$k is $v";
     }
}

Leave a Reply

Your email address will not be published. Required fields are marked *