BenMorel
BenMorel

Reputation: 36574

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.

Upvotes: 0

Views: 398

Answers (1)

Barmar
Barmar

Reputation: 781761

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

Upvotes: 1

Related Questions