PHP: how to move an array pointer inside a foreach loop?

$animals = array('cat', 'dog', 'horse', 'elephant');
foreach($animals as $animal)
{
   var_dump($animal);
   next($animals);
}

The above code: cat, dog, horse, elephant. I thought that the function nextshould move the internal pointer $animalsand so I should get this output instead of: cat, horse.

How to make $ animals internal pointer move forward (and back) so that it is affected in foreach?

EDIT 1:

From the manual:

Since foreach relies on a pointer to an internal array, changing it within a loop can lead to unexpected behavior.

However, I think this is what I need to do.

EDIT 2:

In the section "Your common sense" I will provide a more detailed explanation of my problem. Here is some psuedo code:

array $foos;

start loop of $foos
 - do thing #1
 - do thing #2
 - do thing #3
 - keep doing thing #3 while the current value of $foos in the loop meets a certain criteria
loop

, , № 3. , , for ($i = 0 ... .

+3
6

ArrayIterator & shy; Docs, seekable & shy; Docs.

, , , :

foreach ($iterator as $current) {
    $iterator->next();
}

. , Iterator & shy; Docs .

+8

foreach . , foreach C-style for. , foreach, , .

$animals = array('cat', 'dog', 'horse', 'elephant');
for ($animal = current($animals), $index = key($animals); 
       $animal; 
       $animal = next($animals), $index = key($animals)) {
  print "$index:";
  var_dump($animal);
  next($animals);
} 

:

0:string(3) "cat"
2:string(5) "horse"

, foreach, . for , ; a while , , , .

+6

, , , 0, false "", false .

"" for. reset() , , foreach. for , . key() null, . .

$animals = array('cat', 'dog', 'horse', 'elephant');
for (reset($animals); key($animals) !== null; next($animals)) {
    $animal = current($animals);
    var_dump($animal);
    next($animals);
}

:

string(3) "cat"
string(5) "horse"
+4

, , "continue" if- foreach.

$skip=array ('dog', 'elephant');
$animals = array('cat', 'dog', 'horse', 'elephant');
foreach($animals as $animal)
{
   if (in_array($animal, $skip)) {
       continue;
   }
   var_dump($animal);
}

:

string(3) "cat" 
string(5) "horse"

2 :

$skip=array ('dog', 'elephant');
$animals = array('cat', 'dog', 'horse', 'elephant');
foreach($animals as $animal)
{
   if (!in_array($animal, $skip)) {
        var_dump($animal);
   }

}
0

&

foreach ($variable as $key => &$value) {

}

Now $valuelink to $variable[$key]address

0
source

You do not need to increment the pointer manually at the end of the foreach loop - this is done automatically. You do not need anything else:

foreach($animals as $animal) {
    var_dump($animal)
}
-1
source

All Articles