开发者

PHP getting values from an array with even keys?

开发者 https://www.devze.com 2023-04-02 05:20 出处:网络
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:

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";
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号