Search code examples
phparraysforeachkey

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

  • 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
    }