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.
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)) {
...
}
}
Try this
$images = glob($dir.'/*.jpg');
if (count($images))
foreach($images as $img) {
Use GLOB_ONLYDIR
as flag in your first foreach to get only directories:
foreach (glob('img/gallery/*',GLOB_ONLYDIR) as $dir) {