Created
January 26, 2011 09:32
-
-
Save beingzoe/796472 to your computer and use it in GitHub Desktop.
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
// PHP: Remove Values from Array | |
// 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. | |
// our initial array | |
$arr = Array("blue", "green", "red", "yellow", "green", "orange", "yellow", "indigo", "red"); | |
print_r($arr); | |
// remove the elements who's values are yellow or red | |
$arr = array_diff($arr, array("yellow", "red")); | |
print_r($arr); | |
// optionally you could reindex the array | |
$arr = array_values($arr); | |
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 ) | |
From Pete Graham xXx | |
of Optimus Pete http://tech.petegraham.co.uk/2007/03/22/php-remove-values-from-array/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment