php how do you remove an array element in a foreach loop 3f

Solutions on MaxInterview for php how do you remove an array element in a foreach loop 3f by the best coders in the world

showing results for - "php how do you remove an array element in a foreach loop 3f"
Ronnie
06 Oct 2018
1Instead of doing foreach() loop on the array, it would be faster to use array_search() to find the proper key. On small arrays, I would go with foreach for better readibility, but for bigger arrays, or often executed code, this should be a bit more optimal:
2
3$result=array_search($unwantedValue,$array,true);
4if($result !== false) {
5  unset($array[$result]);   
6}
7
8The strict comparsion operator !== is needed, because array_search() can return 0 as the index of the $unwantedValue.
9
10Also, the above example will remove just the first value $unwantedValue, if the $unwantedValue can occur more then once in the $array, You should use array_keys(), to find all of them:
11
12$result=array_keys($array,$unwantedValue,true)
13foreach($result as $key) {
14  unset($array[$key]);
15}
16
17Check http://php.net/manual/en/function.array-search.php for more information.