How to remove array element by value

How to remove array element by value

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:

  1. Search for the key in the array using the array_search() function
  2. Assign the search result to the variable $delete_key
  3. 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.

Posts on similar topics

Are you having problems with your WordPress site? Do you need additional functionality? A custom plugin or a new page?
Then write to me via the feedback form, and I will try to help you.

Write a comment

Your email address will not be published. Required fields are marked *