0

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.

2
  • array_walk? php.net/manual/en/function.array-walk.php Commented Jul 16, 2021 at 21:33
  • 1
    @Andy How does that help. The question doesn't want to get the keys, it wants to create keys in a new array. Commented Jul 16, 2021 at 21:35

1 Answer 1

1

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

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.