'PHP getting values from an array with even keys?

Is there an easy way to loop through the values of an array using foreach but only targeting the even keys. For example an array like this:

[0] => val0
[1] => val1
[2] => val2
[3] => val3
[4] => val4

etc...

how could i loop through only even keys such as: 0, 2 and 4?

Thanks in advance :)



Solution 1:[1]

In your foreach you can get the key too, just check whether thats even or not.

foreach($array as $key => $value)
{
  if($key%2 != 0) //The key is uneven, skip
    continue;
 //do your stuff
}

Solution 2:[2]

this save 50% from looping

$even = range(0, count($arr), 2);
foreach ($even as $i)
{
  echo $arr[$i]; // etc
}

Solution 3:[3]

I see that there are already 2 answers that would do the trick, but here's another one, not using foreach():

for ($i = 0, $c = count($array); $i < $c; $i += 2)

Solution 4:[4]

for ($i=0; array_key_exists($i, $array); $i+=2) {
    echo $array[$i] . "\n";
}

Solution 5:[5]

function getEven(array $data): array
{
    return array_filter($data, static function ($key) {
        return ($key % 2 === 0);
    }, ARRAY_FILTER_USE_KEY);
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 TJHeuvel
Solution 2 ajreal
Solution 3
Solution 4 str
Solution 5 thiago tanaka