Php Next() Not Working
Solution 1:
The problem is that you are using next($images)
within a foreach ($images ...)
statement, thus modifying the internal array pointer. This may lead to unexpected behavior, as pointed out in the documentation on foreach:
As foreach relies on the internal array pointer, changing it within the loop may lead to unexpected behavior.
This illustrates your problem, using foreach
and next
:
$images = array('one', 'two', 'three', 'four');
foreach ($imagesas$image) {
$next = next($images);
echo"$image => $next", PHP_EOL;
}
Output:
one => three
two => four
three =>
four =>
One may think that just replacing the next()
with current()
would help, but alas:
foreach ($imagesas$image) {
$next = current($images);
echo"$image => $next", PHP_EOL;
}
Output:
one => two
two => two
three => two
four => two
According to a comment on the foreach
documentation page, there used to be a notice on said page stating that:
Unless the array is referenced, foreach operates on a copy of the specified array and not the array itself. foreach has some side effects on the array pointer. Don't rely on the array pointer during or after the foreach without resetting it.
Don't know why that was removed, but if we use a reference for $image
then it actually works (note the &
):
foreach ($imagesas &$image) {
$next = current($images);
echo"$image => $next", PHP_EOL;
}
Output:
one => two
two => three
three => four
four =>
But then maybe an old school for loop just makes more sense:
for ($i = 0; $i < count($images); $i++) {
$nextIndex = $i + 1;
$next = ($nextIndex < count($images)) ? $images[$nextIndex] : null;
$image = $images[$i];
echo"$image => $next", PHP_EOL;
}
Output:
one => two
two => three
three => four
four =>
Output from PHP 5.5.20.
Solution 2:
$images = sort(glob($dirname . "*.jpg"));
Post a Comment for "Php Next() Not Working"