Home > Backend Development > PHP Tutorial > How Can I Filter a PHP Array to Keep Only Elements with a Value of 2, Preserving Original Keys?

How Can I Filter a PHP Array to Keep Only Elements with a Value of 2, Preserving Original Keys?

DDD
Release: 2024-12-15 06:17:09
Original
835 people have browsed it

How Can I Filter a PHP Array to Keep Only Elements with a Value of 2, Preserving Original Keys?

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";
}
Copy after login

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
Copy after login

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!

source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template