PHP
Extract Column from Array of Objects/Arrays in PHP
Efficiently extract a single column or property from an array of associative arrays or objects into a new indexed array using PHP's powerful `array_column()` function.
<?php
$records = [
['id' => 101, 'first_name' => 'John', 'last_name' => 'Doe'],
['id' => 102, 'first_name' => 'Jane', 'last_name' => 'Smith'],
['id' => 103, 'first_name' => 'Peter', 'last_name' => 'Jones']
];
// Extract only 'first_name' column
$firstNames = array_column($records, 'first_name');
echo "First Names:
";
print_r($firstNames);
// Extract 'last_name' column and use 'id' as keys for the new array
$lastNamesById = array_column($records, 'last_name', 'id');
echo "
Last Names by ID:
";
print_r($lastNamesById);
// Example with objects (can be achieved by converting objects to arrays first or custom logic if not simple public properties)
// For simple objects, array_column can sometimes work directly if object properties are public
class User {
public $id; public $name; public $email;
public function __construct($id, $name, $email) {
$this->id = $id; $this->name = $name; $this->email = $email;
}
}
$users = [
new User(1, 'Alice', '[email protected]'),
new User(2, 'Bob', '[email protected]'),
new User(3, 'Charlie', '[email protected]'),
];
// Extract names from objects (PHP 7.0+ array_column supports object properties)
$userNames = array_column($users, 'name');
echo "
User Names from Objects:
";
print_r($userNames);
/*
Output:
First Names:
Array
(
[0] => John
[1] => Jane
[2] => Peter
)
Last Names by ID:
Array
(
[101] => Doe
[102] => Smith
[103] => Jones
)
User Names from Objects:
Array
(
[0] => Alice
[1] => Bob
[2] => Charlie
)
*/
?>
How it works: The `array_column()` function in PHP provides an incredibly efficient way to extract a single column from a multi-dimensional array or an array of objects. It takes the input array, the key/property name of the column to retrieve, and optionally, a key to use as the index for the new array. This eliminates the need for manual loops when you want to create a flat list of specific values (like all user IDs or product names), significantly simplifying data manipulation and improving readability.