BN83
BN83

Reputation: 902

foreach folder echo foreach image

I'm currently using this

foreach (glob('img/gallery/*') as $dir) {
    $folder = str_replace('img/gallery/', '', $dir);
    foreach (glob($dir.'/*.jpg') as $img)  {
        $img1 = str_replace('img/gallery/'.$folder.'/', '', $img);
        $img1 = str_replace('.jpg', '', $img1);
        $img = str_replace(' ', '%20', $img);?>
        <a class="portfolio" title="<?=$img1?>" href="<?=$img?>">
            <li class="mix <?=$folder?>" 
                data-cat="<?=$folder?>" 
                style="height:145px;width:145px;float:left;margin-right:2.5px;margin-left:2.5px;margin-bottom:5px; background:url(<?=$img?>);background-size:cover;">
            </li>
        </a>
    <? }
}

And it's working fine doing exactly what I need, getting all of the files and folder names and displaying them, the problem is now that i've got:

Warning: Invalid argument supplied for foreach() in index.php on line 188

Displaying in the source code, but it's all working. Line 188 is the second foreach.

Upvotes: 0

Views: 237

Answers (3)

ojovirtual
ojovirtual

Reputation: 3362

Use GLOB_ONLYDIRas flag in your first foreach to get only directories:

foreach (glob('img/gallery/*',GLOB_ONLYDIR) as $dir) {

Upvotes: 1

Marc B
Marc B

Reputation: 360612

Are there any files in your subdirs? e.g. /img/gallery/somefile, which you then try to glob again with img/gallery/somefile/*.jpg, which would fail the second glob, returning a boolean false and triggering your error message.

You need to check if what you're globbing internally is actually a dir, e.g.

foreach(glob(...) as $dir) {
    if (issdir($dir)) {
         ...
    }
}

Upvotes: 2

user3252833
user3252833

Reputation: 129

Try this

$images = glob($dir.'/*.jpg');
if (count($images))
foreach($images as $img) {

Upvotes: 1

Related Questions