In this post, we will see how to filter a value from an array in PHP. The solution should return a new array without the specified value. Assume that the array can contain multiple items with the specified value.

1. Using array_filter() function

The standard solution to filter elements of an array is using the array_filter() function, which works by iterating over each value in the array and passing them to the callback function.

Following is a simple example demonstrating this:

Download  Run Code

 
As evident from the above output, the resulting array has gaps. This is because the array_filter() function preserves array keys, which results in an associative array. To resolve this, it is recommended to reindex the resultant array using the array_values() function, as demonstrated below:

Download  Run Code

 
For associative arrays, the code remains similar:

Download  Run Code

2. Using array_diff() function

Another alternative is to use the array_diff() function to filter array elements by their value. It computes the difference between two arrays and return the values in array which are not present in the other array.

The idea is to convert the specified value into an array and compare it with the original array using the array_diff() function. The following code demonstrates this:

Download  Run Code

 
Note that the array_diff() function results in an associative array. To resolve this, reindex the resultant array using the array_values() function.

Download  Run Code

 
Here’s an example using the associative arrays.

Download  Run Code

 
Finally, if you need to filter an array using keys, you can use the array_diff_key() function. Here’s a working example:

Download  Run Code

That’s all about filtering a value from an array in PHP. Refer this post post to in-place remove a specific element from an array by its value in PHP.