Home > Backend Development > PHP Tutorial > How to Filter a Two-Dimensional Array in PHP by a Specific Value?

How to Filter a Two-Dimensional Array in PHP by a Specific Value?

Mary-Kate Olsen
Release: 2024-11-19 04:57:02
Original
400 people have browsed it

How to Filter a Two-Dimensional Array in PHP by a Specific Value?

Filtering a Two-Dimensional Array by Value

Often, when dealing with multidimensional data, it becomes necessary to filter specific values. Filtering a two-dimensional array by name key is a common scenario.

Solution

PHP's powerful array_filter function can be employed to perform this operation. It takes an array and a callback function as input. The callback function evaluates each element of the input array and returns true or false, indicating whether that element should be included in the resulting filtered array.

In our case, we want to filter the array by the name key. The following callback function checks if the name key of the array element matches the desired value:

$searchValue = 'CarEnquiry'; // Change this to the desired name value

$callback = function ($var) use ($searchValue) {
    return ($var['name'] == $searchValue);
};
Copy after login

This callback function can then be passed to array_filter:

$filteredArray = array_filter($inputArray, $callback);
Copy after login

Handling Interchangeable Search Values

The original requirement specified a fixed search value, but it's common to allow interchangeable values. To achieve this, the callback function can be modified:

$filterBy = 'CarEnquiry'; // Current filter value

$callback = function ($var) use ($filterBy) {
    return ($var['name'] == $filterBy);
};
Copy after login

By passing this callback to array_filter, we can filter the array based on the specified $filterBy variable.

The above is the detailed content of How to Filter a Two-Dimensional Array in PHP by a Specific Value?. 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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template