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

前端 未结 6 2012
野的像风
野的像风 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条回答
  •  既然无缘
    2020-12-08 09:47

    Well no body said it but if you don't mind altering the array and if we want to start from the second element of the given array:

    unset($array[key($array)]);
    foreach($array as $key=>$value)
    {
        //do whatever
    }
    

    if you do mind, just add,

    $saved = $array;
    unset($array[key($array)]);
    foreach($array as $key=>$value)
    {
        //do whatever
    }
    $array = $saved;
    

    Moreover if you want to skip a given known index, just subtitute

    key($array)
    

    by the given index

提交回复
热议问题