Search code examples
phparraysglob

How to scan directory and save only image file names to array with php?


I am working on a script that scans a specific directory and saves each image file name to an array. The problem is, I have two txt files in the directory as well. I only want the image file name in the array, I need to exclude the txt files. Because of that, I can't use scandir. Here is what I have so far:

$images = glob($post_dir . "{*.jpg}", GLOB_BRACE);
$listImages=array();
foreach($images as $image){
    $listImages[]=$image;
}

foreach ($listImages as $singleImg) {
    echo $singleImg;
}

I think the problem might actually be in setting the $images variable. In the first foreach, if do echo $image; I don't get anything returned.

EDIT: Also, if there is a better way to accomplish what I am trying to accomplish please feel free to share. I am not set on only using glob.


Solution

  • I think with glob you can just do:

    $post_dir = 'giraffe-images/';
    $images = glob($post_dir . '*.jpg');
    foreach($images as $image){
      echo $image;
    }
    

    As for your situation, $listImages isn't an array after the first foreach loop because you're doing:

    $listImages = $image;
    

    I think you mean to do:

    $listImages[] = $image;