PHP

Index Array By Column

admin by @admin ADMIN
2d ago
May 31, 2026
Public
0 0 up · 0 down Sign in to vote
Rekey a list of rows by one of their column values, so $byId[42] gives the row with id=42. Equivalent to array_column($rows, null, $key).
PHP
Raw
<?php
function indexBy(array $rows, string $key): array {
    $out = [];
    foreach ($rows as $row) {
        if (isset($row[$key])) $out[$row[$key]] = $row;
    }
    return $out;
}

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

$byId = indexBy($users, 'id');
echo $byId[20]['name'];   // Bob
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.