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开发者_C百科 as: 0, 2 and 4?
Thanks in advance :)
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
}
this save 50% from looping
$even = range(0, count($arr), 2);
foreach ($even as $i)
{
echo $arr[$i]; // etc
}
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)
function getEven(array $data): array
{
return array_filter($data, static function ($key) {
return ($key % 2 === 0);
}, ARRAY_FILTER_USE_KEY);
}
for ($i=0; array_key_exists($i, $array); $i+=2) {
echo $array[$i] . "\n";
}
精彩评论