Skip to content
Advertisement

Index an array using a callback function to get the key

Is there a built-in PHP function that does the following?

function array_index(array $values, callable $getKey): array
{
    $result = [];

    foreach ($values as $value) {
        $result[$getKey($value)] = $value;
    }

    return $result;
}

I think I’ve reviewed all array_*() functions, but am surprised that this use case is not covered by any native function.

Advertisement

Answer

There’s no built-in function that does this in one step. But you can use array_map() to get the new keys from the function, and array_combine() to merge those with the original values to create the associative array.

$result = array_combine(array_map($getKey, $values), $values);
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement