How to start a foreach loop at a specific index in PHP

前端 未结 6 2018
野的像风
野的像风 2020-12-08 08:59

I am writing a foreach that does not start at the 0th index but instead starts at the first index of my array. Is there any way to offset the loop\'s starting p

6条回答
  •  猫巷女王i
    2020-12-08 09:41

    In a foreach you cant do that. There are only two ways to get what you want:

    1. Use a for loop and start at position 1
    2. use a foreach and use a something like if($key>0) around your actual code

    A foreach does what its name is telling you. Doing something for every element :)

    EDIT: OK, a very evil solution came just to my mind. Try the following:

    foreach(array_reverse(array_pop(array_reverse($array))) as $key => $value){
        ...
    }
    

    That would reverse the array, pop out the last element and reverse it again. Than you'll have a element excluding the first one.

    But I would recommend to use one of the other solutions. The best would be the first one.

    And a variation: You can use array_slice() for that:

    foreach(array_slice($array, 1, null, true) as $key => $value){
        ...
    } 
    

    But you should use all three parameters to keep the keys of the array for your foreach loop:

提交回复
热议问题