PHP
Extract a Specific Column of Values from an Array of Associative Arrays
Easily extract all values from a specific key (like a column in a database table) into a new simple array from a multi-dimensional PHP array using the built-in `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]'],
['id' => 4, 'name' => 'Alice', 'email' => '[email protected]']
];
// Get all user names
$names = array_column($users, 'name');
echo "User names:
";
print_r($names);
// Get all user IDs, using 'email' as the keys for the new array
$idsByEmail = array_column($users, 'id', 'email');
echo "
User IDs by email:
";
print_r($idsByEmail);
// You can also get a unique list of names
$uniqueNames = array_unique(array_column($users, 'name'));
echo "
Unique user names:
";
print_r($uniqueNames);
?>
How it works: The `array_column()` function is highly efficient for extracting a single "column" of values from a multi-dimensional array or an array of objects. It takes the input array, the key whose values you want to retrieve, and an optional third argument for the key to use as the new array's keys. This is particularly useful for quickly getting lists of IDs, names, or other properties, and can be combined with `array_unique` to get distinct values.