Get next element in foreach loop

前端 未结 9 547
猫巷女王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:04

    A foreach loop in php will iterate over a copy of the original array, making next() and prev() functions useless. If you have an associative array and need to fetch the next item, you could iterate over the array keys instead:

    foreach (array_keys($items) as $index => $key) {
        // first, get current item
        $item = $items[$key];
        // now get next item in array
        $next = $items[array_keys($items)[$index + 1]];
    }
    

    Since the resulting array of keys has a continuous index itself, you can use that instead to access the original array.

    Be aware that $next will be null for the last iteration, since there is no next item after the last. Accessing non existent array keys will throw a php notice. To avoid that, either:

    1. Check for the last iteration before assigning values to $next
    2. Check if the key with index + 1 exists with array_key_exists()

    Using method 2 the complete foreach could look like this:

    foreach (array_keys($items) as $index => $key) {
        // first, get current item
        $item = $items[$key];
        // now get next item in array
        $next = null;
        if (array_key_exists($index + 1, array_keys($items))) {
            $next = $items[array_keys($items)[$index + 1]];
        }
    }
    

提交回复
热议问题