Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Efficient way to delete multiple elements from PHP array

Tags:

arrays

php

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?

like image 365
Feanne Avatar asked Apr 10 '12 14:04

Feanne


2 Answers

You should simply 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 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.

like image 90
Jon Avatar answered Oct 04 '22 20:10

Jon


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 the elements from $exclude_file_array that are not in $files.

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

Its better than your own function and loops.

like image 29
GoSmash Avatar answered Oct 04 '22 21:10

GoSmash