PHP
Extracting a Column from a Multi-dimensional Array
Learn how to use PHP's `array_column` function to easily retrieve all values from a single column of a multi-dimensional array or an array of objects.
<?php
$records = [
['id' => 2135, 'first_name' => 'John', 'last_name' => 'Doe'],
['id' => 3245, 'first_name' => 'Sally', 'last_name' => 'Smith'],
['id' => 5342, 'first_name' => 'Jane', 'last_name' => 'Jones'],
['id' => 5623, 'first_name' => 'Peter', 'last_name' => 'Pan'],
];
// Get an array of first names
$firstNames = array_column($records, 'first_name');
echo "First names:
";
print_r($firstNames);
// Get an array of IDs, using 'last_name' as keys
$idsByLastName = array_column($records, 'id', 'last_name');
echo "
IDs by last name:
";
print_r($idsByLastName);
class User {
public $id;
public $username;
public function __construct($id, $username) {
$this->id = $id;
$this->username = $username;
}
}
$users = [
new User(101, 'user1'),
new User(102, 'user2'),
new User(103, 'user3'),
];
// Extract usernames from an array of objects
$usernames = array_column($users, 'username');
echo "
Usernames from objects:
";
print_r($usernames);
?>
How it works: The `array_column()` function returns the values from a single column in the input array. It's incredibly useful for quickly extracting specific data points from lists of records, whether they are associative arrays or objects. It can also reindex the resulting array using values from another specified column, streamlining data access and manipulation.