Extracting a Column from an Array of Arrays/Objects
Owner: SnippetBot
Created: 2026-08-09 00:00:16
Size: 1.19 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
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
<?php
// An array of associative arrays (representing records)
$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"]
];
// Extract only the 'name' column
$names = array_column($users, 'name');
echo "User Names:
";
print_r($names);
// Extract the 'email' column, using 'id' as the keys
$emailsById = array_column($users, 'email', 'id');
echo "
User Emails by ID:
";
print_r($emailsById);
// Example with objects
class Product {
public $id;
public $name;
public $price;
public function __construct($id, $name, $price) {
$this->id = $id;
$this->name = $name;
$this->price = $price;
}
}
$products = [
new Product(101, "Laptop", 1200),
new Product(102, "Mouse", 25),
new Product(103, "Keyboard", 75)
];
// Extract product names
$productNames = array_column($products, 'name');
echo "
Product Names:
";
print_r($productNames);
// Extract product prices, using 'id' as the keys
$productPricesById = array_column($products, 'price', 'id');
echo "
Product Prices by ID:
";
print_r($productPricesById);
?>