PHP
Extract Column Values from Multidimensional Arrays
Efficiently extract a specific column's values from an array of associative arrays or objects using PHP's `array_column` function.
<?php
$users = [
['id' => 1, 'name' => 'Alice', 'email' => '[email protected]'],
['id' => 2, 'name' => 'Bob', 'email' => '[email protected]'],
['id' => 3, 'name' => 'Charlie', 'email' => '[email protected]']
];
// Extract all 'name' values
$names = array_column($users, 'name');
// $names will be: ['Alice', 'Bob', 'Charlie']
// Extract 'email' values, using 'id' as the keys of the new array
$emailsById = array_column($users, 'email', 'id');
// $emailsById will be: [1 => '[email protected]', 2 => '[email protected]', 3 => '[email protected]']
// Example with objects (can cast to array if needed, or iterate)
class User {
public $id;
public $name;
public $email;
public function __construct($id, $name, $email) {
$this->id = $id; $this->name = $name; $this->email = $email;
}
}
$userObjects = [
new User(4, 'David', '[email protected]'),
new User(5, 'Eve', '[email protected]')
];
// array_column works directly on arrays of objects too, accessing public properties.
$userObjectNames = array_column($userObjects, 'name');
// $userObjectNames will be: ['David', 'Eve']
print_r($names);
print_r($emailsById);
print_r($userObjectNames);
How it works: The `array_column` function in PHP is a highly efficient way to retrieve all values for a single key from an array of associative arrays or objects. It can optionally use another column's values as the keys for the resulting array, making it incredibly useful for quickly transforming data, such as creating lookup tables or generating lists for dropdowns from database results or API responses.