PHP Foreach loop take an additional step forward from within the loop
Basically I have a foreach loop in PHP and I want to:
开发者_如何学Cforeach( $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.
Not sure if you simply want to do just "some stuff" with the first element, only "some more stuff" with the last element, and both "some stuff" and "some more stuff" with every other element. Or if you want to do "some stuff" with the first, third, fifth elements, and "some more stuff" with the second, fouth, sixth elements, etc.
$i = 0;
foreach( $x as $y => $z )
if (($i % 2) == 0) {
// Do some stuff
} else {
// Do some more stuff
}
$i++;
}
Ok, following up on my comment on Pekka's solution, here is one that takes into account the fact that the array might be associative. It's not pretty, but it works. Suggestions on how to improve this are welcomed!
<?php
$y = array(
'1'=>'Hello ',
'3'=>'World ',
'5'=>'Break? ',
'9'=>'Yup. '
);
$keys = array_keys($y);
$count = count($y);
for ($i = 0; $i < $count; $i++) {
// Current element
$index = $keys[$i];
echo "Current: ".$y[$index]; // The current element
if (array_key_exists($i+1, $keys)) {
$index2 = $keys[$i+1];
echo "Next: ".$y[$index2]; // The next element
}
if (array_key_exists($i+2, $keys)) {
$index3 = $keys[$i+2];
echo "Nextnext: ".$y[$index3]; // The element after next
}
}
?>
try something like...
for ($i=0, $i<count($x); $i++)
{
// do stuff with $x[$i]
// do stuff with $x[$i+1], unless you're on the last element of the array
}
reset($arr);
while(list($firstindex,$firstvalue) = each($arr)){
list($secondindex,$secondvalue) = each($arr);
//do something with first & second.
}
精彩评论