Marcus Haase
Marcus Haase

Reputation: 35

PHP: Search in 2-Dimensional array but only look in specific key

I want to search through a 2-dimensional array, but I only want to search in a specific field in the 2nd Dimension. If found, I would like to return the Key. No need to go on from there, I only need the first occurence but I wouldn't mind to get all occurences either.

The Array might look like this:

$array = [
    0 => ['value' => 'x', 'foo' => 'bar'],
    1 => ['value' => 'y', 'foo' => 'bar'],
    2 => ['value' => 'z', 'foo' => 'x'],
];

Now my first thought would be something like this:

function myCustomArraySearch($array, $searchkey, $searchvalue) {
    foreach ($array as $key => $value) {
        if ($value[$searchkey] == $searchvalue) {
            return $key;
        }
    }
    return false;
}

echo myCustomArraySearch($array, 'value', 'x');

I'm sure, there is a more elegnt solution. Any ideas?

Upvotes: 1

Views: 88

Answers (3)

AbraCadaver
AbraCadaver

Reputation: 79004

Here is one way that returns a single key:

$result = array_search('x', array_column($array, 'value'));

This will return multiple keys:

$result = array_keys(array_column($array, 'value'), 'x');

If you don't have PHP >= 5.5.0 needed for array_column() then use this in it's place:

array_map(function($v) { return $v['value']; }, $array)

Upvotes: 4

Christian
Christian

Reputation: 1577

Your code is working fine so this code just does it in less lines. Only works for PHP 5.5+.

function myCustomArraySearch($array, $searchkey, $searchvalue) {
    $cols   = array_column($array, $searchkey);
    $result = array_search($searchvalue, $cols);
    return $result;
}

Of course, if you wanted to return the array it found and not just the index you would just return like so:

function myCustomArraySearch($array, $searchkey, $searchvalue) {
    $cols   = array_column($array, $searchkey);
    $result = array_search($searchvalue, $cols);
    return $array[$result];
}

Upvotes: 2

yosbel
yosbel

Reputation: 339

The functions below returns the position of the first occurrence:

1 - Using foreach iteration and array_serach

function search1($array, $key, $value) {
    foreach ($array as $k => $arr) {
        if (array_search($value, $arr) != false) {
            return $k;
        }
    }
    return false;
}

2 - Using array_map, array_key_exists and array_search.

function search2($array, $key, $value) {
    $mapped = array_map(function($arr) use ($key, $value) {
        return (array_key_exists($key, $arr) && $arr[$key] == $value)
               ? true
               : false;
    },
    $array);    

    return array_search(true, $mapped);
}

Upvotes: 2

Related Questions