yes i love technology

PHP: Remove Values from Array

March 22nd, 2007 by Pete

If you need to remove elements from an array that have a particular value(s) here’s a neat way of doing it without any looping:

PHP:
  1. // our initial array
  2. $arr = Array("blue", "green", "red", "yellow", "green", "orange", "yellow", "indigo", "red");
  3. print_r($arr);
  4.  
  5. // remove the elements who's values are yellow or red
  6. $arr = array_diff($arr, array("yellow", "red"));
  7. print_r($arr);
  8.  
  9. // optionally you could reindex the array
  10. $arr = array_values($arr);
  11. print_r($arr);

This is the output from the code above:
Array ( [0] => blue [1] => green [2] => red [3] => yellow [4] => green [5] => orange [6] => yellow [7] => indigo [8] => red )
Array ( [0] => blue [1] => green [4] => green [5] => orange [7] => indigo )
Array ( [0] => blue [1] => green [2] => green [3] => orange [4] => indigo )

Pete Graham xXx

Posted in Tech, php, arrays, programming | 11 Comments »