In this post, we will see how to remove a specific element from an array by its value in PHP.

If the array contains only a single element with the specified value, you can use the array_search() function with unset() function to remove it from an array. The array_search() function searches the array for a given value and returns the first corresponding key if present in the array, false otherwise. If the value is found in the array, you can remove it using the unset() function.

Download  Run Code

 
For the plain arrays, the code remains similar:

Download  Run Code

 
Note that the resulting array has holes since the numerical keys in the array are preserved. You can replace the unset() call with the array_splice() function, which removes a portion of the array and doesn’t preserve numerical keys.

Download  Run Code

2. Using foreach construct

If your array can contain multiple elements with the specified value, you can use a simple foreach loop to iterate over the array, and unset all matching values.

 
Note that in each iteration of the loop, the value of the current element is compared with the given value, and it unsets the matching items. The code can be shortened using the array_keys() function:

Download  Run Code

 
Here’s an example using plain arrays:

Download  Run Code

That’s all about removing a specific element from an array in PHP.

 
Related Posts:

Filter a value from an array in PHP