Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP Foreach loop take an additional step forward from within the loop

Tags:

foreach

php

Basically I have a foreach loop in PHP and I want to:

foreach( $x as $y => $z )  
    // Do some stuff  
    // Get the next values of y,z in the loop  
    // Do some more stuff  
like image 246
Chris Avatar asked Jan 26 '26 11:01

Chris


2 Answers

It's not practical to do in a foreach.

For non-associative arrays, use for:

for ($x = 0; $x < count($y); $x++)
 {
   echo $y[$x];  // The current element

   if (array_key_exists($x+1, $y))
    echo $y[$x+1]; // The next element

   if (array_key_exists($x+2, $y))
    echo $y[$x+2]; // The element after next

 }

For associative arrays, it's a bit more tricky. This should work:

$keys = array_keys($y); // Get all the keys of $y as an array

for ($x = 0; $x < count($keys); $x++)
 {
   echo $y[$keys[$x]];  // The current element

   if (array_key_exists($x+1, $keys))
    echo $y[$keys[$x+1]]; // The next element

   if (array_key_exists($x+2, $keys))
    echo $y[$keys[$x+2]]; // The element after next

 }

When accessing one of the next elements, make sure though that they exist!

like image 111
Pekka Avatar answered Jan 28 '26 02:01

Pekka


use the continue keyword to skip the rest of this loop and jump back to the start.

like image 32
Dagg Nabbit Avatar answered Jan 28 '26 02:01

Dagg Nabbit



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!