Remove values from an array

Prototype.js library has a handy function called Array.without, which "produces a new version of the array that does not contain any of the specified values.".

Quite often one might need to do the same thing in PHP. Here is a function for those occasions.

  1. <?php
  2.  
  3. /**
  4.  * Remove specified values from the array
  5.  *
  6.  * @param array $array  Array to update
  7.  * @param array $values Array of values to remove
  8.  * @return array
  9.  */
  10. function array_without(array $array, $values)
  11. {
  12.     $values = (array) $values;
  13.    
  14.     foreach ($values as $value) {
  15.         do {
  16.             $key = array_search($value, $array);
  17.            
  18.             if ($key !== false) {
  19.                 unset($array[$key]);
  20.             }
  21.         } while ($key !== false);
  22.     }
  23.    
  24.     return $array;
  25. }

First thing we convert $values to an array. This means that if you pass a string to this function, it will become an array with one entry ($values[0]).

Next we loop through the list of values that we want to remove. Because of the fact that array_search function only finds the first occurence of the value, we need to run it as until we can't find any instances of $value.

As the last thing we return the modified array.

A quick example:

Let's assume we have an array, which looks like this:

  1. $a = array('apple', 'pear', 'potato', 'tomato');

If we wanted to get rid of 'potato' and 'tomato', we would run array_without the following way:

  1. $a = array_without($a, array('potato', 'tomato'));

or like this, if we only wanted to remove 'tomato':

  1. $a = array_without($a, 'tomato');

Pretty easy, eh!

Comments
No comments
Name
Email (required)
will not be published
Website
Recaptcha
you will only be required to fill it in once in this session

You can use [code][/code] tags in your comments