Search code examples
phpforeachgalleryglob

Use an foreach loop inside another one foreach in PHP?


I have created a simple gallery using PHP where the images inside a folder (let's call it main folder) displays on a specific part on the website, and that works really great.

But I decided to go a bit further and create different categories based on the folders that are inside the main folder, and the PHP script finds all of the folders and creates the divs named after the folders using the code;

<?php
foreach(glob('images/*', GLOB_ONLYDIR) as $directories) {
    echo ("<div id='$directories'>");
    echo ("<h1>$directories</h1>");
    foreach(glob('$directories/*') as $image) {

        echo ("<img src='$image' width='300'>");

    }
    echo ("</div>");

}
?>

But the foreach inside it does not display anything, although it works fine outside of the first foreach. The result I am looking for is that the PHP searches through the folder images after folder, and when it finds one, create a div, and inside it write the folders name and then show all of the images that are inside of that specific folder - and then continue to the next and repeat, does anyone know what is wrong?

I have searched through the Internet and this site after answers, but all of them have been more advanced, and none of them using glob. Therefore I am asking it here now.

Thanks in advance!


Solution

  • The foreach loops are ok but you need to use double quotes when you want to interpolate a variable into a string. I guess you just missed that. The inner foreach should look like this:

    foreach(glob("$directories/*") as $image) {
    

    If you ask me, I would name the variable $directory (singular). This seems more appropriate.