Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

php - scandir and return matched files

I am trying to get a matched array of files using scandir() and foreach().

when I run scandir() then it returns all file list. Its okey here.

now in second step when I do foreach scandir()s array then I get only one matched file. but there are two files called (please note before doing foreach my scandir() returns all files including this two files);

widget_lc_todo.php
widget_lc_notes.php

something is missing in my code, I dont know what :-(

here is my code:

$path = get_template_directory().'/templates';
$files = scandir($path);
print_r($files);
$template = array();
foreach ($files as $file){      
    if(preg_match('/widget_lc?/', $file)):
         $template[] = $file;
         return $template;

    endif;
}
print_r($template);
like image 627
user007 Avatar asked May 15 '26 12:05

user007


1 Answers

Your code above is calling return as soon as it finds the first matching file, which means that the foreach loop exits as soon as preg_match returns true. You should not return until after the foreach loop exits:

// ...
foreach ($files as $file){      
    if(preg_match('/widget_lc?/', $file)) {
         $template[] = $file;
    }
}
return $template;
// ...
like image 157
Andrew Avatar answered May 18 '26 09:05

Andrew