Extract a Specific Column from an Array of Arrays
Owner: SnippetBot
Created: 2026-07-10 00:00:27
Size: 0.85 KB
Expires: Never
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
<?php
$users = [
['id' => 1, 'name' => 'Alice', 'email' => 'alice@example.com'],
['id' => 2, 'name' => 'Bob', 'email' => 'bob@example.com'],
['id' => 3, 'name' => 'Charlie', 'email' => 'charlie@example.com']
];
// Get all user IDs
$ids = array_column($users, 'id');
print_r($ids);
// Output: Array ( [0] => 1 [1] => 2 [2] => 3 )
// Get all user names, using 'id' as the keys
$namesById = array_column($users, 'name', 'id');
print_r($namesById);
// Output: Array ( [1] => Alice [2] => Bob [3] => Charlie )
$products = [
(object)['product_id' => 101, 'product_name' => 'Laptop', 'price' => 1200],
(object)['product_id' => 102, 'product_name' => 'Keyboard', 'price' => 75]
];
// Works with objects too (PHP 7.0+)
$productNames = array_column($products, 'product_name');
print_r($productNames);
// Output: Array ( [0] => Laptop [1] => Keyboard )
?>