Search code examples
phpsyntaxforeachcarouselglob

Invalid syntax - Glob image directory scan for carousel


I have the following syntax error with this code:

Warning: natcasesort() expects parameter 1 to be array, boolean given in Website/assets/country-gallery-js.php on line 14

Warning: Invalid argument supplied for foreach() in Website/assets/country-gallery-js.php on line 15

    <?php $thumbs = glob("img/thumb/*.{jpg,png,gif}", GLOB_BRACE); ?>
    <?php
    if(count($thumbs)) {
      natcasesort($thumbs);
      foreach($thumbs as $thumb) {?>
            <li class="item">
              <a class="fancybox" rel="gallery1" href="img/large/<?php echo basename($thumb) ?>">
                  <img src="<?php echo $thumb ?>" class="img-circle" width="100%" alt="" />
              </a>
          </li>
        <?php
        }
    }
    else {
      echo "Sorry, no images to display!";
    }
    ?>

I am unsure as to why. The code scans a folder for images to display as a carousel. It scans a thumbnail and large image folder for lightbox. When images are in the folder, it works like a treat.. when the folder is empty it should echo the 'else' text code. Instead it displays this syntax.

Can anyone help me figure this one out and stop the syntax from appearing?


Solution

  • Use is_array instead of count 
    <?php $thumbs = glob("img/thumb/*.{jpg,png,gif}", GLOB_BRACE); ?>
    <?php
    if (is_array($thumbs)) {
        natcasesort($thumbs);
        foreach ($thumbs as $thumb) {
            ?>
            <li class="item">
                <a class="fancybox" rel="gallery1" href="img/large/<?php echo basename($thumb) ?>">
                    <img src="<?php echo $thumb ?>" class="img-circle" width="100%" alt="" />
                </a>
            </li>
    
            <?php
        }
    } else {
        echo "Sorry, no images to display!";
    }
    ?>