array_column() Does Way More Than Grab a Column
Most people know array_column as "pluck one field from an array of rows". That's the least interesting third of what it does. The function has two more tricks that replace loops I see written by hand constantly.
Trick 1: the third parameter re-indexes
$users = [
['id' => 7, 'name' => 'Anna', 'email' => 'anna@example.com'],
['id' => 12, 'name' => 'Ben', 'email' => 'ben@example.com'],
];
// null = keep whole rows, third param = which field becomes the key
$byId = array_column($users, null, 'id');
// [7 => ['id' => 7, 'name' => 'Anna', ...], 12 => [...]]
Passing null as the column keeps the entire row and re-keys the array by any field. This is the pure-PHP twin of PDO's FETCH_UNIQUE, and it turns "find the row with id X" from a loop into an array access.
Trick 2: two fields = instant lookup map
$nameById = array_column($users, 'name', 'id'); // [7 => 'Anna', 12 => 'Ben']
$idByEmail = array_column($users, 'id', 'email'); // flip any two fields into a map
Dropdown options, translation tables, foreign-key resolution before a bulk insert - one line each. I reach for this multiple times a week.
Trick 3: it reads objects too
Since PHP 7, array_column works on arrays of objects, reading public properties (and even __get/__isset-backed virtual ones):
$titles = array_column($posts, 'title'); // from Post objects
$postsById = array_column($posts, null, 'id'); // objects re-keyed by property
Combined with array_map for anything computed:
// emails of admins, keyed by id, in two declarative steps
$admins = array_filter($users, fn ($u) => $u['role'] === 'admin');
$emailById = array_column($admins, 'email', 'id');
The gotchas (small but real)
- Rows missing the requested column are silently skipped - no warning, the result is just shorter. Great for sparse data, surprising when it's a typo'd key.
- Index-column values are cast to valid array keys: floats truncate, and null keys become empty strings. Re-index by clean scalar ids only.
- Duplicate keys: later rows overwrite earlier ones (opposite of FETCH_UNIQUE, which keeps the first). Remember which tool you're holding.
My rule of thumb: any foreach whose body is only $result[$x] = $y is array_column (or array_combine) wearing a trench coat. The named function states the intent, skips the temp-variable ceremony, and runs in C instead of interpreted PHP. Delete the loop.
Full-stack web developer sharing practical tutorials and building tools that ship.
Got something on your mind?
My inbox is open - no forms disappearing into the void here.
- Just say hello Found a tutorial useful? Spotted a mistake? Tell me.
- Hire me for a project Have something custom in mind? Let's talk scope and timelines.
- Product support Bought something here? I'll help you get it running.
I usually reply within 1-2 business days.