Get next element in foreach loop

前端 未结 9 561
猫巷女王i
猫巷女王i 2020-11-30 03:56

I have a foreach loop and I want to see if there is a next element in the loop so I can compare the current element with the next. How can I do this? I\'ve read about the cu

9条回答
  •  悲哀的现实
    2020-11-30 04:21

    You could get the keys of the array before the foreach, then use a counter to check the next element, something like:

    //$arr is the array you wish to cycle through
    $keys = array_keys($arr);
    $num_keys = count($keys);
    $i = 1;
    foreach ($arr as $a)
    {
        if ($i < $num_keys && $arr[$keys[$i]] == $a)
        {
            // we have a match
        }
        $i++;
    }
    

    This will work for both simple arrays, such as array(1,2,3), and keyed arrays such as array('first'=>1, 'second'=>2, 'thrid'=>3).

提交回复
热议问题