PHP: foreach array objects, how to move the internal pointer to the next?

I need to create a loop and an array of objects. In some cases inside the loop, I need to move the internal pointer to the next element in the array. How to do it?

foreach($objects as $object) { // TODO: move internal pointer to next one? // next($objects) doesn't work } 
+4
source share
5 answers

You cannot move the array pointer, but you can skip the iteration :

 foreach ($objects as $object) { if (!interesting($object)) { continue; } // business as usual } 

If you need to decide whether to skip the following iteration, you can do something like this:

 $skip = false; foreach ($objects as $object) { if ($skip) { $skip = false; continue; } // business as usual if (/* something or other */) { $skip = true; } } 

First I have to check if there is better logic for expressing what you want. If this does not exist, the @netcoder list each example is a shorter way to do this.

+9
source

As already mentioned, you can use a for loop (only if you have number keys) or continue . Another alternative is to use the list and each iteration method, which allows you to move the array pointer with next , prev , etc. (Since it does not create a copy of an array of type foreach ). ):

 $array = array(1,2,3,4,5); while (list($key, $value) = each($array)) { echo $value; next($array); } 

It will display:

 024 
+5
source

next ($ objects)

next - advance the internal pointer of the array array

0
source

Now, I understand what you want;), two other solutions

 $c = count($array); for ($i = 0; $i < $c; $i += 2) { $item = $array[$i]; } foreach (range(0, count($array), 2) as $i) { $item = $array[$i]; } 
0
source

Use for a loop, for example:

 for($i = 0; $i < sizeof($array); $i++) { echo $array[$i]->objectParameter; $i++; //move internal pointer echo $array[$i]->objectParameter; $i++; //move internal pointer again echo $array[$i]->objectParameter; //$i++; //no need for this because for loop does that } 
0
source

Source: https://habr.com/ru/post/1337231/


All Articles