1

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?

1

3 Answers 3

4

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)
Sign up to request clarification or add additional context in comments.

1 Comment

There seams to be a small typo here: array_map(function($v) { return $v['value']; }, $array)
2

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);
}

Comments

2

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];
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.