Efficient way to remove multiple elements from a PHP array

I have a dynamically generated array of file names, let's say something like this:

$files = array("a-file","b-file","meta-file-1", "meta-file-2", "z-file"); 

I have a few specific file names that I want to remove from the array:

 $exclude_file_1 = "meta-file-1"; $exclude_file_2 = "meta-file-2"; 

So, I will always know the values ​​of the elements that I want to reset, but not the keys.

I am currently considering 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, use array_keys and undo :

 $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 methods create the desired result.

I'm just wondering which one will be more efficient (and why)?

Or maybe there is another, more efficient way to do this?

How is there possibly a way to have multiple search values ​​in an array_search function?

+7
source share
2 answers

You should just use array_diff :

 $files = array("a-file","b-file","meta-file-1", "meta-file-2", "z-file"); $exclude_file_1 = "meta-file-1"; $exclude_file_2 = "meta-file-2"; $exclude = array($exclude_file_1, $exclude_file_2); $filtered = array_diff($files, $exclude); 

One of the bad things about PHP is that it has function functions for doing special things, but sometimes it can be convenient.

When you are faced with a similar situation (you have found a solution after defining the relevant function, but you are not sure if there is something better), it’s nice to look at the sidebar of the function list on php.net at your leisure.A simple reading of function names can bring huge dividends.

+17
source

Use array_diff ()

 $files = array("a-file","b-file","meta-file-1", "meta-file-2", "z-file"); $exclude_file_array = array("meta-file-1", "meta-file-2"); 

will return an array with all elements from $ exclude_file_array that are not in $ files.

 $new_array = array_diff($files, $exclude_file_array); 

Better than your own function and loops.

+1
source

All Articles