PHP
Extracting Data with array_column
Efficiently extract a single column of values from an array of associative arrays or objects using PHP's array_column() function, optionally using another column as keys.
<?php
$records = [
['id' => 101, 'name' => 'Alice', 'email' => '[email protected]'],
['id' => 102, 'name' => 'Bob', 'email' => '[email protected]'],
['id' => 103, 'name' => 'Charlie', 'email' => '[email protected]'],
];
// Extracting a single column (e.g., 'name')
$names = array_column($records, 'name');
// Result: ['Alice', 'Bob', 'Charlie']
echo "Names:
";
print_r($names);
// Extracting a column and using another column as keys (e.g., 'id' as keys for 'email')
$emailsById = array_column($records, 'email', 'id');
// Result: [101 => '[email protected]', 102 => '[email protected]', 103 => '[email protected]']
echo "
Emails by ID:
";
print_r($emailsById);
// Handling missing keys (returns null for non-existent columns)
$ages = array_column($records, 'age');
// Result: [null, null, null]
echo "
Ages (missing column):
";
print_r($ages);
?>
How it works: The `array_column()` function is ideal for quickly retrieving values from a single column within a multi-dimensional array, such as an array of database records. It can also be used to index the resulting array by the values of another specified column, making it extremely useful for transforming data into more accessible formats. This function is particularly efficient compared to manually looping through the array for the same task.