It seems like a fairly trivial task, and such a function should be built into PHP’s core — but unfortunately, it’s not. So we have to find our own solutions for implementing this functionality. One such solution for removing an array element by its value is shown below:
if(($delete_key = array_search($search_value, $my_array)) !== false)
{
unset($my_array[$delete_key]);
}You could say it’s just two lines — and the functionality is ready.
Let’s take a closer look at the code above:
array_search() — searches for a given value in an array and returns the corresponding key if found
unset() — deletes a variable or an array element
In the "if" statement, we perform three actions at once:
- Search for the key in the array using the array_search() function
- Assign the search result to the variable $delete_key
- Check the result’s type (to confirm it’s not false)
And finally, if the value of “$delete_key” is not equal to “false,” we remove the array element by key.
