Tirenty2 Tirenty2 - 6 months ago 11
PHP Question

PHP: Find next in foreach loop

I've got the following code to select all images from a directory.

$folder = "fotoalbum/";
$files = array_diff(scandir($folder, 1), array(".", ".."));
foreach ($files as $file) {
$nextFile = current($files);
$fileInfo = pathinfo($folder . "/" . $file);
echo "<img src=".$fileInfo['basename']." /></a>";
}


How can I find the next picture in this folder? I've tried current($allebilder), next($allebilder) and prev($allebilder), but nothing will work?

Answer

Try this:

foreach ($allebilder as $k=>$bild) {
$nextbild = $k < count($allebilder) - 1 ? $allebilder[$k+1] : null;
....
}

ofc, you can do:

$prevbild = $k > 0 ? $allebilder[$k-1] : null;