Home >Backend Development >PHP Tutorial >How Can I Filter a Two-Dimensional PHP Array Based on a Specific Key\'s Value?

How Can I Filter a Two-Dimensional PHP Array Based on a Specific Key\'s Value?

Patricia Arquette
Patricia ArquetteOriginal
2024-11-21 12:17:09661browse

How Can I Filter a Two-Dimensional PHP Array Based on a Specific Key's Value?

Filtering a Two-Dimensional Array by Value

Filtering a two-dimensional array by value requires selecting specific elements based on a particular criterion. In this case, we aim to filter an array based on a value in the "name" key.

Implementation

To achieve this, we can leverage PHP's native array_filter function, which takes an array and a callback function as arguments. The callback function defines the filtering criteria.

$new = array_filter($arr, function ($var) {
    return ($var['name'] == 'CarEnquiry');
});

In this example, the callback checks if the "name" key of each element in the $arr array is equal to 'CarEnquiry'. If it matches, the element is included in the filtered array $new.

Dynamic Filtering

To make the filtering more versatile, allowing different search values, we can encapsulate the value to be filtered in a variable:

$filterBy = 'CarEnquiry'; // or Finance

$new = array_filter($arr, function ($var) use ($filterBy) {
    return ($var['name'] == $filterBy);
});

By assigning the desired filter value to the $filterBy variable, you can dynamically change the filtering criteria.

With this approach, you can efficiently filter two-dimensional arrays by any desired value within a specified key.

The above is the detailed content of How Can I Filter a Two-Dimensional PHP Array Based on a Specific Key's Value?. 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