Using php's array_search on an array of objects

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

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

Tags:

Php

Arrays