Home >Backend Development >PHP Tutorial >How Can I Filter a PHP Array to Keep Only Elements with a Specific Value, Preserving Original Keys?
Filtering an Array Based on a Value Condition with PHP
An array can be filtered according to a specified condition using built-in PHP functions. Consider the following scenario:
Objective:
Filter an array to retain elements where the value equals 2 and remove all others, preserving the original keys.
Original Array:
$fullArray = array('a' => 2, 'b' => 4, 'c' => 2, 'd' => 5, 'e' => 6, 'f' => 2);
Expected Result:
array('a' => 2, 'c' => 2, 'f' => 2);
Solution:
To achieve this, we can utilize the array_filter() function with a custom callback function that evaluates the value condition. Here's an example:
function filterArray($value){ return ($value == 2); } $filteredArray = array_filter($fullArray, 'filterArray'); foreach($filteredArray as $k => $v){ echo "$k = $v"; }
In this solution:
This solution provides a straightforward and efficient way to filter an array based on a specific value condition, retaining the original keys, thus meeting the desired outcome.
The above is the detailed content of How Can I Filter a PHP Array to Keep Only Elements with a Specific Value, Preserving Original Keys?. For more information, please follow other related articles on the PHP Chinese website!