PHP Remove Item from an Array

When working with arrays in PHP, you will encounter times when you need to easily remove known values from that array. There are a couple of quick techniques I use to accomplish this.

The first, uses the PHP function array_diff(). When using array_diff to remove an item from an array, you pass your current array as the first parameter and an array containing only that value you want to remove as the second.

We'll start with our intial array, a list of dog breeds:

$dogs = array('poodle','beagle','great dane','dachshund');

Now, we'll use array_diff to get rid of the poodle to form a list of hounds

$hounds = array_filter($dogs,'gethounds'); // --> array(3) { [1]=>  string(6) "beagle" [2]=>  string(10) "great dane" [3]=>  string(9) "dachshund" }

The second method utilizes the handy array_filter() function for more complex removal. When using array_filter to remove an item from an array, we pass our current array as the first parameter and the filtering callback function as a string as the second parameter.

For this example, we will keep it simple and stick to checking whether or not the type of dog is a poodle. If it is not a poodle, our filtering function will return TRUE and be added to the resulting array.

function gethounds($dog){
  if($dog != 'poodle')
    return TRUE;
}
$hounds = array_filter($dogs,'gethounds'); // --> array(3) { [1]=>  string(6) "beagle" [2]=>  string(10) "great dane" [3]=>  string(9) "dachshund" }

Related Posts

  • Remove Fancy Quotes in WordPress
  • Valid Flash in Firefox
  • Using PHP Dynamic Variables
  • Select All Checkboxes with Prototype JS
  • First Letter of a String in JavaScript: test.CharAt() vs test[]
  • Leave a Reply