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:
-
// our initial array
-
-
// remove the elements who's values are yellow or red
-
-
// optionally you could reindex the array
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
Comments 13
Great tip, thanks.
Posted 15 May 2007 at 8:39 pm ¶One suggestion: array_values() will reindex a numerical array nicely, but will remove all key strings from the array and replace them with numbers. If you need to preserve the key names (strings), or reindex the array if all keys are numerical, use array_merge(), maybe even:
$arr = array_merge(array_diff($arr, array("yellow", "red")));I’ve tested this and it works nicely for arrays with mixed indexes (strings and numeric), good tip yourself!
Posted 16 May 2007 at 8:11 am ¶I was trying to use the unset function but now after reading this i am going to try the array_diff function.
Posted 09 Mar 2008 at 3:54 am ¶I used used this even though I wanted to remove only one user selected value.
$arr = array_diff( $arr, array(“$removal”) );
Works very well. Thanks for thinking to post it.
Posted 29 May 2008 at 9:08 pm ¶Thanks, lots better than a loop. You are first hit on “Remove Values from Array”
Posted 01 Jun 2008 at 10:48 pm ¶Thanks! First hit on Google “php remove a value in array”!
Posted 06 Jun 2008 at 1:28 pm ¶Great tip. Helped me out on a project of mine.
Posted 29 Jun 2008 at 6:01 pm ¶I have been looking for a better way to do this (without defining a function). Thanks
Posted 25 Jul 2008 at 4:46 am ¶Thats a great tip. Thanks a lot!
Posted 27 Aug 2008 at 2:03 pm ¶Nice tip… thanks!
BTW, your the first hit for “php delete value in array”, also.
Posted 15 Dec 2008 at 2:22 pm ¶“I was trying to use the unset function but now after reading this i am going to try the array_diff function.” — same here, and this worked — thanks!
Posted 26 Jan 2009 at 6:41 pm ¶Many thanks for posting this code snippet. It helped me out and it works well.
Posted 31 Jul 2009 at 7:14 pm ¶Thank you for this succinct bit of code. It was exactly what I was looking for.
Posted 15 Aug 2010 at 7:13 pm ¶Trackbacks & Pingbacks 1
[...] I found an array_diff example on Peter Grahams blog while I was writing a simple site configuration manager in cakePHP. I needed to reduce an array to certain values based on a passed condition. Peter Grahams example showed me exactly what I need. [...]
Post a Comment