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);
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;
// ...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With