-3

Possible Duplicate:
Finding a file with a specific name with any extension

i've this code for put into an array all the files contained into a directory

$directory =  "./";
$ourDirList = scandir($directory); 
$arraylistafiles=array();

foreach($ourDirList as $ourItem) 
{  
   if (is_file($ourDir . $ourItem)) 
   {$arraylistafiles[]=$ourItem;}
}  

but if i want to put only the file that have ".jpg" extension, what i can do?

Community
  • 1
  • 1
user1088417
  • 55
  • 2
  • 9
  • "what can I do?" well, you could use the search function because this has been answered a dozens times or more. – Gordon Dec 30 '11 at 18:10

4 Answers4

6

Using PHP's glob() you can avoid the is_file() call because glob will only return files that actually exist in the directory. There is no need to create a UDF (user defined function) in your case.

$dir = './';
foreach(glob($dir.'*.jpg') as $file) {
  print $file . "\n";
}

UPDATE

From your comment it's clear that you don't understand how glob() works. You can achieve what you're trying to do like this:

$arraylistafiles = glob($dir.'*.jpg');

  • i wrote foreach(glob($ourDir.'*.jpg') as $ourItem) { if (is_file($ourDir . $ourItem)) {$arraylistafiles[]=$ourItem;} } but donesn't work – user1088417 Dec 30 '11 at 18:40
  • You don't need all that extra code ... `glob()` gives you the array of files (`$arraylistafiles`) you're trying to create. Also, "doesn't work" is ambiguous -- an actual error message is infinitely more helpful. You could do the same thing like this: `$arraylistafiles = glob($dir.'*.jpg');` –  Dec 30 '11 at 19:11
0
 if(is_file($ourDir.$ourItem) && substr($ourItem,-4) == '.jpg') {
     //
 }
Cyclonecode
  • 29,115
  • 11
  • 72
  • 93
0

You can use bellow function.

public function getFileList($dirpath,$list_ignore,$list_allowed_ext)
    {
        $filelist = array();
        if ($handle = opendir(dirname ($dirpath))) 
        {
           while (false !== ($file = readdir($handle)))
              {
                  if (!is_dir($file) && !in_array($file,$list_ignore) && in_array(strtolower(end(explode('.',$file))),$list_allowed_ext))
                    {
                        $filelist[] = $file;
                    }
              }
            closedir($handle);
        }

        return $filelist;
    }

Implementation will be looks like..

$fileTypes = array ("jpg");
$list_ignore = array ('.','..');
$fileList = getFileList("./",$list_ignore,$fileTypes);

Cheers!

Prasad Rajapaksha
  • 6,118
  • 10
  • 36
  • 52
0

First you have to check for the file extension for the file in foreach array. . If the extension is jpg then add that item into the new array. . . Hope you understand. .

Abdul
  • 1