PHP
Extract a Column of Values from an Array of Arrays in PHP
Master the `array_column` function in PHP to quickly pull all values for a specific key from an array of associative arrays, creating a new simple array with desired data.
<?php
$users = [
[
'id' => 101,
'name' => 'Alice',
'email' => '[email protected]'
],
[
'id' => 102,
'name' => 'Bob',
'email' => '[email protected]'
],
[
'id' => 103,
'name' => 'Charlie',
'email' => '[email protected]'
]
];
// Extract all user names
$names = array_column($users, 'name');
print_r($names);
// Expected output: Array ( [0] => Alice [1] => Bob [2] => Charlie )
// Extract all user IDs and use 'name' as the key for the new array
$userEmailsById = array_column($users, 'email', 'id');
print_r($userEmailsById);
// Expected output: Array ( [101] => [email protected] [102] => [email protected] [103] => [email protected] )
?>
How it works: The `array_column` function in PHP is specifically designed to extract a single column from an array of arrays (or objects). It takes the input array, the key/column name whose values you want to retrieve, and an optional third argument for the key to use as the indexes of the returned array. This makes it incredibly efficient for tasks like getting a list of all names or mapping IDs to email addresses without writing manual loops.