PHP array_column: Extract Column from Multidimensional Array
Extracting a single column of values from a multidimensional array is
a common task in PHP development. This article provides a quick and
clear guide on how to use PHP’s built-in array_column()
function to accomplish this task efficiently, complete with practical
code examples.
Understanding array_column()
The array_column() function returns the values from a
single column of an input array, typically a multidimensional array or
an array of objects. It eliminates the need for writing verbose
foreach loops to isolate specific data.
Syntax
array_column(array $input, int|string|null $column_key, int|string|null $index_key = null): array$input: The multidimensional array (or array of objects) from which to draw values.$column_key: The key of the column of values you want to extract. Passnullto return complete arrays or objects (useful when resetting array keys using the third parameter).$index_key: (Optional) The column to use as the index/keys for the returned array.
Practical Examples
1. Basic Column Extraction
To extract a simple list of values from a specific key, pass the multidimensional array as the first argument and the key name as the second argument.
$users = [
['id' => 101, 'name' => 'Alice', 'role' => 'Admin'],
['id' => 102, 'name' => 'Bob', 'role' => 'Editor'],
['id' => 103, 'name' => 'Charlie', 'role' => 'User']
];
// Extract all names
$names = array_column($users, 'name');
print_r($names);Output:
Array
(
[0] => Alice
[1] => Bob
[2] => Charlie
)
2. Extracting a Column with Custom Keys
You can use the third parameter to define custom keys for the returned array. This is highly useful for re-indexing arrays by a unique identifier.
$users = [
['id' => 101, 'name' => 'Alice', 'role' => 'Admin'],
['id' => 102, 'name' => 'Bob', 'role' => 'Editor'],
['id' => 103, 'name' => 'Charlie', 'role' => 'User']
];
// Extract names indexed by user ID
$namesById = array_column($users, 'name', 'id');
print_r($namesById);Output:
Array
(
[101] => Alice
[102] => Bob
[103] => Charlie
)
3. Extracting from an Array of Objects
array_column() also works seamlessly with arrays of
objects. It can access public properties of objects directly.
class User {
public $id;
public $username;
public function __construct($id, $username) {
$this->id = $id;
$this->username = $username;
}
}
$users = [
new User(1, 'johndoe'),
new User(2, 'janedoe'),
];
$usernames = array_column($users, 'username');
print_r($usernames);Output:
Array
(
[0] => johndoe
[1] => janedoe
)