How to filter a two dimensional array by value

Use PHP's array_filter function with a callback.

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

Edit: If it needs to be interchangeable, you can modify the code slightly:

$filterBy = 'CarEnquiry'; // or Finance etc.

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

<?php



    function filter_array($array,$term){
        $matches = array();
        foreach($array as $a){
            if($a['name'] == $term)
                $matches[]=$a;
        }
        return $matches;
    }

    $new_array = filter_array($your_array,'CarEnquiry');

?>

If you want to make this a generic function use this:

function filterArrayByKeyValue($array, $key, $keyValue)
{
    return array_filter($array, function($value) use ($key, $keyValue) {
       return $value[$key] == $keyValue; 
    });
}

Tags:

Php

Arrays