I have a dynamically generated array of filenames, let’s say it looks something like this:
$files = array("a-file","b-file","meta-file-1", "meta-file-2", "z-file");
I have a couple of specific filenames that I want discarded from the array:
$exclude_file_1 = "meta-file-1";
$exclude_file_2 = "meta-file-2";
So, I’ll always know the values of the elements I want discarded, but not the keys.
Currently I’m looking at a couple of ways to do this.
One way, using array_filter and a custom function:
function excludefiles($v)
{
if ($v === $GLOBALS['exclude_file_1'] || $v === $GLOBALS['exclude_file_2'])
{
return false;
}
return true;
}
$files = array_values(array_filter($files,"excludefiles"));
Another way, using array_keys and unset:
$exclude_files_keys = array(array_search($exclude_file_1,$files),array_search($exclude_file_2,$files));
foreach ($exclude_files_keys as $exclude_files_key)
{
unset($files[$exclude_files_key]);
}
$files = array_values($page_file_paths);
Both ways produce the desired result.
I’m just wondering which one would be more efficient (and why)?
Or perhaps there is another, more efficient way to do this?
Like maybe there’s a way to have multiple search values in the array_search function?
You should simply use
array_diff:One of the bad things about PHP is that it has zillions of functions to do specific little things, but that can also turn out to be convenient sometimes.
When you come across a situation like this (you have found a solution after locating a relevant function, but you are unsure if there is something better), it’s a good idea to browse the function list sidebar on php.net at leisure. Just reading the function names can pay huge dividends.