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
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!
use the continue keyword to skip the rest of this loop and jump back to the start.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With