Saturday, 22 April 2017

PHP remove specific item from array





I have an array like : [312, 401, 1599, 3]



With array_diff( [312, 401, 1599, 3], [401] ) I can remove a value, in my example I removed the value 401.



But if I have this : [312, 401, 401, 401, 1599, 3], how can remove just one time the value 401 ?




It is not important if I remove the first or last value, I just need to remove ONE 401 value, and if I want to remove all 401 values, I have to remove three times.



Thanks !


Answer



With array_search you can get the first matching key of the given value, then you can delete it with unset.



if (false !== $key = array_search(401, $array)) {
unset($array[$key]);
}


No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...