Josh Schumacher: A PHP Developer

The biggest and the best in the Northwest

Josh Schumacher: A PHP Developer random header image

PHP – Delete selected items from an array

March 22nd, 2007 · 30 Comments

I was enlightened the day I discovered array_filter. You may find yourself with an array of values and you want to delete some of those values from the array. There is no ‘delete element from array’ function built into php but you can use an even more powerful function, array_filter.

Let’s look at a simple example. I have an array containing values, some are numeric, some might not be. I only want my array to contain the valid numeric entries and I want to delete the other values. PHP has a helper function we are going to be utilizing, is_numeric.

  1. $data = array(42, "foo", 96, "", 100.96, "php");
  2.  
  3. // Filter each value of $data through the function is_numeric
  4. $numeric_data = array_filter($data, "is_numeric");
  5.  
  6. // Re-key the array so the keys are sequential and numeric (starting at 0)
  7. $numeric_data = array_values($numeric_data);
  8.  
  9. // Print out the new, filtered data
  10. print_r($numeric_data);

The output from above is:

Array
(
    [0] => 42
    [1] => 96
    [2] => 100.96
)

Pretty handy function. Notice how I ran my data through the function array_values, before that function was run, the keys were (0,2,4).

Another example with a user defined function. I have defined a collection of tags and I want my tag collection to only contain tags that match the criteria the user has requested.

  1. $tagCollection = array("AJAX", "Analytics", "CSS", "Javascript", "JoshSchumacher.com", "PHP", "Prototype", "Web 2.0");
  2.  
  3. // Custom function used to filter the $tagCollection based on query sent to page
  4. function strTagMatch($val)
  5. {
  6.   $query = isset($_REQUEST['Tags']) ? $_REQUEST['Tags'] : '';
  7.   return (stripos($val, $query) !== false);
  8. }
  9.  
  10. $tags = array_filter($tagCollection, "strTagMatch");

Voila! Deleting elements from an array has never been easier.

For more information, see the php documentation on array_filter.

Tags: PHP

30 responses so far ↓

  • 1 evll // May 11, 2007 at 1:08 am

    Actually, instead of using user defined function, you could use array_diff().

    For example: array_diff( array(‘a’, ‘b’), array(‘b’) ) would delete ‘b’ in much easier way…

  • 2 Josh.Schumacher // May 11, 2007 at 5:44 am

    Correct, you could use array_diff() to delete an element if you know what the elements are that you are deleting. I chose to use an array_filter() though because you can do conditional deleting. For example, you can delete it only if it’s not numeric or if it’s greater than 5 characters.

    You can’t perform conditional deletes using an array_diff() but it is a simple way to delete items you do know the value.. Thanks for another quick way to delete an item from an array in php.

  • 3 Firass // Jul 20, 2007 at 3:31 pm

    Dude, you need to blog more.

  • 4 Henke // Sep 12, 2007 at 7:40 am

    The arrat_diff function is perfelct for what i.m working on now since it has no objects in the the arrays .

    Thanks for the tip.

  • 5 Mat?ss // Nov 13, 2007 at 5:21 am

    And what about array with keys not indexes?

    array (‘key1′ => ‘value1′, ‘key2′ => ‘value2′);

    how can you delete an item by key not value?

  • 6 Mat?ss // Nov 13, 2007 at 5:23 am

    answer to my own question. array_diff_key i guess..

  • 7 Josh.Schumacher // Nov 13, 2007 at 8:39 am

    If you know exactly which key in an array you want to delete, use unset

    $a = array(‘foo’=>8, ‘bar’=>3245, ‘foobar’=>213);

    To make the array only contain keys ‘foo’ and ‘bar’ just:
    unset($a[‘foobar’]);

  • 8 Salah // Jan 7, 2008 at 4:07 am

    Matiss ,

    The last solution given by Josh is valid. However it has the same problem as array_diff() versus array_filter() in that you have to know the keys in advance.

    To go past that shortcoming, you can use “foreach”.

    foreach ($array as $key => $value) {
    if ($array[$key] == ”’) unset($array[$key]);
    }

    Here we deleted all empty values from the array. But you can specify any condition you want.

  • 9 Mat?ss // Feb 21, 2008 at 11:25 pm

    ok, thx a lot for solutions!

  • 10 Nurul // Mar 6, 2008 at 8:58 am

    Thanks evll , For the quickest solution.

  • 11 mgwalk // Mar 8, 2008 at 8:40 pm

    Nice post but i think the unset function works better for my use!

    Thanks

  • 12 Parag Sawaikar // Dec 8, 2008 at 7:27 pm

    Nice post! It was very helpful.
    Thank You!!

  • 13 tom // Dec 23, 2008 at 5:05 am

    what if one wants to delete a record or row (as in multi-dimentional array)?

  • 14 Jonatas Miguel // Jan 2, 2009 at 3:13 pm

    @tom

    A user named niehztog posted code in the PHP documentation for array_filter that should be able to help you.

  • 15 David Barrett // Feb 10, 2009 at 9:01 pm

    Deleting a particular record from a string array is very straightforward:

    $arr[$id]=”;
    $arr=array_filter(arr);
    $arr=array_values($arr);

    Where $id is the row you wish to delete. array_filter with no callback deletes and FALSE values in the array, and an empty string is FALSE. Using this theory it will work for other array types too – so long as you don’t need any false values left in the array!

  • 16 Artur // Mar 23, 2009 at 9:46 pm

    David,

    Well, yes, looks like it will take care of deleting the data in the array string but it does not get rid of the string, how can that be done? For example, I am looking to remove the $arr[0] alltogether

    thanks

  • 17 Josh Schumacher // Mar 24, 2009 at 3:12 am

    Artur – If you need to completely delete an element from an array, use unset(). So to delete the element 0 from $arr, use: unset($arr[0]);

  • 18 Kaveh Rassoulzadegan // Apr 20, 2009 at 4:09 pm

    You may change your discussion title. It is too global.

    Maybe with something like :

    “Delete selected items from an array with conditions”

    for people looking for unset or array_splice.

  • 19 Cool // Jul 27, 2009 at 5:05 pm

    For example,

    $array = array(abc,cde, efg);

    If i want to remove elements that match with character ‘c’ from an array like above,

    can it be works by using array_filter() and preg_match()?

    Coz from wat i see here is using function within it to remove the elements. so i need to put whole command in current function, right?

    Please correct me if i’m wrong.

  • 20 Josh Schumacher // Jul 27, 2009 at 5:22 pm

    @Cool, yes you can use a combo of array_filter with another helper to remove any elements with the letter ‘c’ from you array above. Here’s some sample code for your use case:

    $array = array(‘abc’,’cde’,’efg’);

    function hasNoC($val) {
    return (stripos($val, ‘c’) === false);
    }

    $clean_array = array_filter($array, “hasNoC”);

  • 21 Cool // Jul 30, 2009 at 4:40 pm

    That’s very helpfu.
    Thanks for the tips.

  • 22 Mike // Aug 28, 2009 at 4:02 pm

    I have used unset() on an array element to remove the element.

    I like your solution!

  • 23 Ben Althauser // Sep 16, 2009 at 5:10 pm

    with an edit from the php array_dif example, here’s a nice comparison and removal script,

    “green”, “red”, “blue”, “red”, “purple”);
    $array2 = array(“b” => “green”, “yellow”, “red”);
    $result = array_diff($array1, $array2);
    $myray[] = implode(“,”,$result);
    echo implode(“,”,$myray);
    ?>

  • 24 web development // Jun 23, 2010 at 8:49 am

    very helpful post! thanks!

  • 25 shaffy // Jul 31, 2010 at 11:22 am

    Thanks for Tips

  • 26 Luca from Italy // Jan 13, 2011 at 12:59 am

    Thank you very much, array_filter is amazing and I didn’t know it!!! :-)

  • 27 kurosaki // Mar 5, 2011 at 7:00 pm

    guys i have also a problem with arrays
    for example my array contains 30 elements and i want to remove the first five regardless of values then
    what should i do

  • 28 Faiz Ahmed // Aug 2, 2012 at 7:35 am

    this is a very useful post.. specially

    $no_pin = count($pin_update_list);

    // var_dump($pin_update_list);

    for ($i = 0; $i < $no_pin; $i++) {
    if ($pin_update_list[$i]['Pin'] == intval($Pin)) {
    unset($pin_update_list[$i]);
    } else {
    $pin_update_list[$i] = $pin_update_list[$i];
    }
    }
    $pin_update_list = array_values($pin_update_list);

  • 29 Dermot // Nov 17, 2012 at 10:51 am

    Thanks Josh for the great post!

    There are also other alternatives to deleting items in an array, as you can read about here:

    http://www.programmerinterview.com/index.php/php-questions/how-to-delete-an-element-from-an-array-in-php/

  • 30 What is the best way to delete array item in PHP? - PHP Solutions - Developers Q & A // Jul 30, 2013 at 4:11 pm

    […] References PHP – Delete selected items from an array […]

Leave a Comment