69

How would I create a function that filters a two dimensional array by value?

Given the following array :

Array
(
    [0] => Array
        (
            [interval] => 2014-10-26
            [leads] => 0
            [name] => CarEnquiry
            [status] => NEW
            [appointment] => 0
        )

    [1] => Array
        (
            [interval] => 2014-10-26
            [leads] => 0
            [name] => CarEnquiry
            [status] => CALL1
            [appointment] => 0
        )

    [2] => Array
        (
            [interval] => 2014-10-26
            [leads] => 0
            [name] => Finance
            [status] => CALL2
            [appointment] => 0
        )

    [3] => Array
        (
            [interval] => 2014-10-26
            [leads] => 0
            [name] => Partex
            [status] => CALL3
            [appointment] => 0
        )

How would I filter the array to only show those arrays that contain a specific value in the name key? For example name = 'CarEnquiry'.

The resulting output would be:

Array
(
    [0] => Array
        (
            [interval] => 2014-10-26
            [leads] => 0
            [name] => CarEnquiry
            [status] => NEW
            [appointment] => 0
        )

    [1] => Array
        (
            [interval] => 2014-10-26
            [leads] => 0
            [name] => CarEnquiry
            [status] => CALL1
            [appointment] => 0
        )

    )

EDIT

I forgot to mention that the search value should be interchangeable - i.e. name = 'CarEnquiry' or name = 'Finance'.

aphextwix
  • 1,838
  • 3
  • 21
  • 27
  • 3
    Use `array_filter()`. http://php.net/manual/en/function.array-filter.php – Jonathan M Dec 12 '14 at 16:31
  • 1
    You know that in your example, none of the `name` properties equal the string `"CarEnquiry"`. They are of the *class* `CarEnquiry`. – Jonathan M Dec 12 '14 at 16:34
  • I answered the exact same question several hours ago: http://stackoverflow.com/a/27440026/4265352 – axiac Dec 12 '14 at 16:35

6 Answers6

156

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);
});
dchesterton
  • 2,070
  • 1
  • 14
  • 13
  • 2
    @Tobias Yes, you could do. `$new = array_filter($arr, function ($var) use ( $filterBy1, $filterBy2 ) { return ($var['name'] == $filterBy1 || $var['name'] == $filterBy2 ) });` – CHEWX Aug 13 '19 at 15:56
  • With reindexing (start at 0) : `$new = array_values(array_filter($arr, function ($var) { return ($var['name'] == 'CarEnquiry'); }));` – kortex Jul 29 '20 at 10:03
5

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; 
    });
}
stacky
  • 236
  • 4
  • 4
  • Excuse me, what is the reserved word 'use' for? I usually use it to refer to namespaces – Daniele Jul 12 '23 at 14:34
  • @Daniele, the keywork 'use' transfer the variables into the callback function. In this case, $key and $keyValue that is 'outside' the callback will be accessible inside the callback. – Steferson Aug 11 '23 at 13:35
3
<?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');

?>
ksealey
  • 1,698
  • 1
  • 17
  • 16
2

Above examples are using the exact word match, here is a simple example for filtering array to find imprecise "name" match.

  $options = array_filter($options, function ($option) use ($name) {
    return strpos(strtolower($option['text']), strtolower($name)) !== FALSE;
  });
bpile
  • 359
  • 3
  • 10
1

array_filter is the function you need. http://php.net/manual/en/function.array-filter.php

Give it a filtering function like this:

function my_filter($elt) {
    return $elt['name'] == 'something';
}
Benoît Latinier
  • 2,062
  • 2
  • 24
  • 36
0
function multi_array_search_with_condition($array, $condition)
{
    $foundItems = array();

    foreach($array as $item)
    {
        $find = TRUE;
        foreach($condition as $key => $value)
        {
            if(isset($item[$key]) && $item[$key] == $value)
            {
                $find = TRUE;
            } else {
                $find = FALSE;
            }
        }
        if($find)
        {
            array_push($foundItems, $item);
        }
    }
    return $foundItems;
}

This my function can use about this problem. You can use:

$filtered = multi_array_search_with_condition(
   $array,
   array('name' => 'CarEnquiry')
);

This will get your filtered items from your 2 dimensional array.

arshovon
  • 13,270
  • 9
  • 51
  • 69
Metin Erbek
  • 84
  • 2
  • 8
  • Why bother with the temporary `true` / `false` declaration? I would not recommend this long-winded solution. (A good piece to include would be a `break`) – mickmackusa Jul 24 '18 at 01:11