Oihana PHP

keyBy.php

Table of Contents

Functions

keyBy()  : array<int|string, mixed>
Indexes the items of an array by a computed key.

Functions

keyBy()

Indexes the items of an array by a computed key.

keyBy(array<int|string, mixed> $items, callable $keyer) : array<int|string, mixed>

The $keyer callback is invoked as fn( $value , $key ) for every entry and must return the new key. Non int|string keys are cast to string. When two items resolve to the same key, the last one wins.

Parameters
$items : array<int|string, mixed>

The array to index.

$keyer : callable

The indexing callback: fn( $value , $key ): int|string.

Tags
example
use function oihana\core\arrays\keyBy;

$users =
[
    [ 'id' => 10 , 'name' => 'Alice' ] ,
    [ 'id' => 20 , 'name' => 'Bob'   ] ,
];

$byId = keyBy( $users , fn( $u ) => $u[ 'id' ] ) ;
// [ 10 => [ 'id' => 10, 'name' => 'Alice' ] , 20 => [ 'id' => 20, 'name' => 'Bob' ] ]
author

Marc Alcaraz (ekameleon)

since
1.0.9
Return values
array<int|string, mixed>

An associative array of computedKey => value.

On this page

Search results