7

http://php.net/manual/en/function.array-search.php allows me to find the first array key based on an array value.

Can this be accomplished with a single PHP function if the value is nested in an object in the array values, or must it be manually performed as I show below?

Thank you

<?php
function getKeyBasedOnName($arr,$name)
{
    foreach($arr as $key=>$o) {
        if($o->name==$name) return $key;
    }
    return false;
}
$json='[
{
"name": "zero",
"data": [107, 31, 635, 203, 2]
},
{
"name": "one",
"data": [133, 156, 947, 408, 6]
},
{"name": "two",
"data": [1052, 954, 4250, 740, 38]
}
]';
$arr=json_decode($json);
var_dump(getKeyBasedOnName($arr,'zero')); //Return 0  
var_dump(getKeyBasedOnName($arr,'one')); //Return 1  
var_dump(getKeyBasedOnName($arr,'two')); //Return 2
var_dump(getKeyBasedOnName($arr,'three')); //Return false
11
  • I believe your function is what needs to be done. Beware if name is not set that will throw a notice. Maybe revise your if to if ( property_exists($o, 'name') && $o->name == $name) {... Commented Aug 5, 2016 at 18:14
  • @cale_b Thanks and point well taken. Wasn't sure if there was some sort of walk/map version of array_search(). Commented Aug 5, 2016 at 18:15
  • Maybe array_filter could be used this way? It'd end up being as verbose as what you've done, because to use an "outside value", you have do put it in a class and wrap it in a function. As an aside, after working in Javascript / Angular more recently, and using the lodash library and finding it super useful, I often lament not having better tools like this. Have considered using this library which ports many of those super-useful functions to php. Commented Aug 5, 2016 at 18:16
  • @cale_b. Yea, maybe. By the way, have you seen php.net/manual/en/book.spl.php? Maybe what you are looking for. Commented Aug 5, 2016 at 18:18
  • There isn't a built in array_usearch function that allows you to supply a compare function. Wouldn't be hard to make one yourself. Commented Aug 5, 2016 at 18:18

3 Answers 3

12

Just for fun, if the array is 0 based and sequential keys:

echo array_search('zero', array_column(json_decode($json, true), 'name'));
  • Extract all the name key values into a single array
  • Search for the name value to return the key

This decodes the JSON into an array. You can decode it to an object after if you need that. As of PHP 7 you can use an array of objects:

echo array_search('zero', array_column(json_decode($json), 'name'));
Sign up to request clarification or add additional context in comments.

3 Comments

I guess this pretty much answers the question, but will likely keep with my simple function. Thanks
No prob. Added PHP 7 example.
I like the PHP 7 solution, and will try to remember it when I go to PHP 7.
6

There's no single built-in function that provides for arbitrary comparison. You can, however, roll your own generic array search:

function array_usearch(array $array, callable $comparitor) {
    return array_filter(
        $array,
        function ($element) use ($comparitor) {
            if ($comparitor($element)) {
                return $element;
            }
        }
    );
}

This has the benefit of returning an array of matches to the comparison function, rather than a single key which you later have to lookup. It also has performance O(n), which is ok.

Example:

array_usearch($arr, function ($o) { return $o->name != 'zero'; });

Comments

0
print_r($json[array_search('zero', array_column(json_decode($json, true), 'name'))]->data);

1 Comment

See Explaining entirely code-based answers. While this might be technically correct, it doesn't explain why it solves the problem or should be the selected answer. We should educate along with helping solve the problem.

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.