Home >Backend Development >PHP Tutorial >How Can I Create a PHP Function to Filter a Two-Dimensional Array Based on Value?

How Can I Create a PHP Function to Filter a Two-Dimensional Array Based on Value?

Linda Hamilton
Linda HamiltonOriginal
2024-11-27 05:44:11691browse

How Can I Create a PHP Function to Filter a Two-Dimensional Array Based on Value?

Creating a Function for Value-Based Filtering of Two-Dimensional Arrays

Filtering specific data from multi-dimensional arrays is a common task in programming. This task can be accomplished using various techniques, including PHP's array_filter function.

Function Creation

To create a function that filters a two-dimensional array by value, follow these steps:

  1. Define the function with the input array as a parameter.
  2. Utilize array_filter with an anonymous or callback function as the second parameter.
  3. Within the callback function, use conditional logic to specify the filtering criteria.

Example Implementation

Consider the following array:

$arr = [
    [
        'interval' => '2014-10-26',
        'leads' => 0,
        'name' => 'CarEnquiry',
        'status' => 'NEW',
        'appointment' => 0
    ],
    [
        'interval' => '2014-10-26',
        'leads' => 0,
        'name' => 'CarEnquiry',
        'status' => 'CALL1',
        'appointment' => 0
    ],
    [
        'interval' => '2014-10-26',
        'leads' => 0,
        'name' => 'Finance',
        'status' => 'CALL2',
        'appointment' => 0
    ],
    [
        'interval' => '2014-10-26',
        'leads' => 0,
        'name' => 'Partex',
        'status' => 'CALL3',
        'appointment' => 0
    ]
];

To filter this array for values containing 'CarEnquiry' in the 'name' key:

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

Customizable Filtering

To make the search value interchangeable, modify the callback function as follows:

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

Now you can use the function to filter the array by any desired value in the 'name' key.

The above is the detailed content of How Can I Create a PHP Function to Filter a Two-Dimensional Array Based on 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