Home >Backend Development >PHP Tutorial >How Can I Filter a PHP Array Based on Value Using `array_filter()`?

How Can I Filter a PHP Array Based on Value Using `array_filter()`?

Barbara Streisand
Barbara StreisandOriginal
2024-12-17 21:38:15661browse

How Can I Filter a PHP Array Based on Value Using `array_filter()`?

Filter Arrays Based on Conditions in PHP

When working with arrays in PHP, it often becomes necessary to filter out elements based on specific conditions. For instance, you may want to remove elements with a value not meeting a certain criterion.

Filtering an Array by a Value

Let's consider an array like the following:

array("a" => 2, "b" => 4, "c" => 2, "d" => 5, "e" => 6, "f" => 2)

Suppose we want to filter this array to keep only elements where the value is equal to 2. We want the result to retain the original keys:

array("a" => 2, "c" => 2, "f" => 2)

To achieve this, PHP provides a built-in function called array_filter(). This function takes two parameters:

  • $array: The array to be filtered.
  • $callback: A callback function that determines which elements to keep.

Creating a Callback Function

For our case, we need a callback function that returns true for elements with a value of 2 and false otherwise. We can define this function as follows:

function filterArray($value){
    return ($value == 2);
}

Applying the Filter

Now, we can use array_filter() with our callback function to filter the array:

$filteredArray = array_filter($fullArray, 'filterArray');

The result is stored in $filteredArray, which contains the desired output:

array("a" => 2, "c" => 2, "f" => 2)

The above is the detailed content of How Can I Filter a PHP Array Based on Value Using `array_filter()`?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn