php - 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 allarray_*()
functions, but am surprised that this use case is not covered by any native function.
Answer
Solution:
There's no built-in function that does this in one step. But you can usearray_map()
to get the new keys from the function, andarray_combine()
to merge those with the original values to create the associative array.
$result = array_combine(array_map($getKey, $values), $values);
Share solution ↓
Additional Information:
Link To Answer People are also looking for solutions of the problem: illuminate\http\exceptions\posttoolargeexception
Didn't find the answer?
Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.
Similar questions
Find the answer in similar questions on our website.
Write quick answer
Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.