I\'m trying to make a gallery using PHP. The images load properly, but the next and previous buttons don\'t seem to work. Clicking next on picture #1 brings you to picture #3 bu
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 ($images as $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 ($images as $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 ($images as &$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.
$images = sort(glob($dirname . "*.jpg"));