Home >Backend Development >PHP Tutorial >PHP program to get all files in a directory and save the results to an array_PHP tutorial
Sometimes at work, we need to batch process files in a certain directory. At this time, we need to find all the files that meet the conditions in the directory and save them into a result set. Then it is convenient for batch processing. The usual method is to save it into an array and then process it in a loop. The process will be recorded below.
//php gets all the files in the directory and saves the results to an array
foreach(glob("./*") as $d){
$tmp=explode(".",$d);
$k=end($tmp);
//If it is a file, and the file extension is jpg png
if(is_file($d)&&in_array($k,array("jpg","png"))){
$files[]=$d;
}
}
echo "
";print_r($files);
The above source code is to list all files with the suffix jpg png in the current directory, save the results as an array and then print them out. The results of this test are printed as follows: