PHP
Extract a Specific Column from a Multidimensional Array
Efficiently extract a single column's values from an array of arrays or objects in PHP using `array_column()`, perfect for lists of IDs or names.
<?php
$records = [
['id' => 101, 'name' => 'Alice', 'score' => 95],
['id' => 102, 'name' => 'Bob', 'score' => 88],
['id' => 103, 'name' => 'Charlie', 'score' => 92]
];
// Get an array of all 'name' values
$names = array_column($records, 'name');
print_r($names);
// Expected Output: Array ( [0] => Alice [1] => Bob [2] => Charlie )
// Get an array of 'score' values, indexed by 'id'
$scoresById = array_column($records, 'score', 'id');
print_r($scoresById);
// Expected Output: Array ( [101] => 95 [102] => 88 [103] => 92 )
?>
How it works: The `array_column()` function returns the values from a single column in the input array. It's especially useful when dealing with arrays of associative arrays (like database query results) where you need to extract a list of specific property values. It can also be used to index the resulting array by another specified column's values.