PHP Function to know the next value of loop?
Let's say I have this foreach loop:
foreach ($lists as $list) {
if (next list item == "test")开发者_运维知识库 {
echo "the next $list item equals 'test'";
}
}
I hope you get what i'm aiming at from the code.
Thanks,
You can use next()
.
Bear in mind this advances the internal pointer, so to rewind it back, use prev()
.
However, in the example below, I used current()
which gets the current pointer of an array. foreach()
seems to increment it once in the body of the construct.
Konforce came up with this idea originally.
The last blank is NULL
, which is good (there is no next member). :)
$lists = range('a', 'f');
foreach($lists as &$value) {
$next = current($lists);
echo 'value: ' . $value . "\n" . 'next: ' . $next . "\n\n";
}
unset($next, $value);
Output
value: a
next: b
value: b
next: c
value: c
next: d
value: d
next: e
value: e
next: f
value: f
next:
CodePad.
For an index based array, it's simple. Use a for
loop or make use of $i => $val
when looping.
For other arrays, you can do something like:
$current = current($lists);
while ($current !== false)
{
$next = next($lists);
echo "$current => $next\n";
$current = $next;
}
although if your array contains the literal value false, it won't work. You will also need to reset
to loop through again.
You can emulate current/next item:
<?php
$lists = range('a', 'f');
foreach ($lists as $next) {
if($list !== NULL) {
if ($next == "test") {
echo "the next $next item equals 'test'";
}
echo 'current: ' . $list . ', next: ' . $next . "\n";
}
$list = $next;
}
?>
Output:
current: a, next: b
current: b, next: c
current: c, next: d
current: d, next: e
current: e, next: f
精彩评论