phparrayssearchmultidimensional-arrayarray-key

Search into multidimensional array comparing two keys without using foreach loop


I have arrays like this:

$actions = array(
    array(
        'type'      => 'checkbox',
        'id'        => 'f0',
        'is_active' => 1
    ),
    array(
        'type'      => 'checkbox',
        'id'        => 'f1',
        'is_active' => 0
    ),
    array(
        'type'      => 'radio',
        'id'        => 'f2',
        'is_active' => 0
    ),
    array(
        'type'      => 'checkbox',
        'id'        => 'f3',
        'is_active' => 1
    ),
    array(
        'type'      => 'text',
        'id'        => 'f4',
        'is_active' => 1
    ),
    array(
        'type'      => 'checkbox',
        'id'        => 'f5',
        'is_active' => 0
    ),
    array(
        'type'      => 'checkbox',
        'id'        => 'f6',
        'is_active' => 1
    )
);

so i need to extract the arrays that has type = 'checkbox' and is_active = 1 only without any "for loop" ..

Any good solution ?


Solution

  • You can use array_filter with callback to return only type which is checkbox.

    $filtered = array_filter($array, function($v){return $v['type'] == 'checkbox' && $v['is_active'] == 1;});
    

    Working example :- https://3v4l.org/idAR4