Created
October 21, 2020 04:04
-
-
Save balwantmeticulosity/7ba4842939d7a45c0c27a5da72397379 to your computer and use it in GitHub Desktop.
PHP: How to search and remove specific element from an array?
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
| $array = array('apple', 'orange', 'strawberry', 'blueberry', 'kiwi'); | |
| 1- | |
| Use array_search to get the key and remove it with unset if found: | |
| if (($key = array_search('strawberry', $array)) !== false) { | |
| unset($array[$key]); | |
| } | |
| array_search returns false (null until PHP 4.2.0) if no item has been found. | |
| And if there can be multiple items with the same value, you can use array_keys to get the keys to all items: | |
| foreach (array_keys($array, 'strawberry') as $key) { | |
| unset($array[$key]); | |
| } | |
| 2- | |
| Use array_diff() | |
| $array = array('apple', 'orange', 'strawberry', 'blueberry', 'kiwi', 'strawberry'); //throw in another 'strawberry' to demonstrate that it removes multiple instances of the string | |
| $array_without_strawberries = array_diff($array, array('strawberry')); | |
| 3- | |
| Use in_array() | |
| if (in_array('strawberry', $array)) | |
| { | |
| unset($array[array_search('strawberry',$array)]); | |
| } | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment