Filtering an Array by a Condition
Filtering an array by a specific condition can be useful in various programming scenarios. This involves retaining specific elements that meet the specified criteria while discarding those that do not.
In this particular case, the objective is to filter an array and only retain elements whose values are equal to 2. The desired output is an array with the keys from the original array preserved.
PHP's Built-in Function: array_filter
PHP offers a built-in function called array_filter() that simplifies this task. It takes two arguments: the input array and a callback function that specifies the filtering criteria.
The callback function should return true if the element meets the condition and false otherwise. In this case, our callback function is filterArray(), which simply checks if the value of the element is equal to 2.
Implementing the Solution
The provided PHP code demonstrates how to use array_filter() to filter the given array:
$fullArray = array('a' => 2, 'b' => 4, 'c' => 2, 'd' => 5, 'e' => 6, 'f' => 2); function filterArray($value) { return ($value == 2); } $filteredArray = array_filter($fullArray, 'filterArray'); foreach ($filteredArray as $k => $v) { echo "$k = $v\n"; }
This code will print the filtered array with only the elements that have a value of 2, preserving their original keys as specified in the note:
a = 2 c = 2 f = 2
The above is the detailed content of How Can I Filter a PHP Array to Keep Only Elements with a Value of 2, Preserving Original Keys?. For more information, please follow other related articles on the PHP Chinese website!