PHP Search Array column for match

If you are using PHP >= 5.5, then you can use the new array_column(), in conjunction with array_keys() and array_map().

Given your array, $array:

$keys = array_keys(array_column($array, 'id'), 1);
$new_array = array_map(function($k) use ($array){return $array[$k];}, $keys);

See demo


Since you have an nested Array you need two iterations:

$filtered = array();
$rows = Your Array;
foreach($rows as $index => $columns) {
    foreach($columns as $key => $value) {
        if ($key == 'id' && $value == '1') {
            $filtered[] = $columns;
        }
    }
}

This should do the job.


I found a much simpler solution that I think is worthwhile sharing with the world

in_array(1, array_column($yourArray, 'id'));

Tested on PHP >= 5.5

Tags:

Php

Arrays

Search