In PHP 8.4, the array_column()
function continues to operate as it did in previous versions, without any changes or new features introduced. This function is used to extract values from a single column in a multi-dimensional array.
Syntax:
array_column(array $array, int|string|null $column_key, int|string|null $index_key = null): array
Parameters:
$array
: The input array containing sub-arrays or objects from which to pull a column of values.$column_key
: The key of the column to retrieve values from. This can be an integer key, a string key name, ornull
. If set tonull
, the function will return complete arrays or objects.$index_key
(optional): The key to use as the index/keys for the returned array. This can be an integer key, a string key name, ornull
. If not provided or set tonull
, the function will use the default integer indexing.
Example:
// Sample array representing a record set
$records = [
[
'id' => 5698,
'first_name' => 'Peter',
'last_name' => 'Griffin',
],
[
'id' => 4767,
'first_name' => 'Ben',
'last_name' => 'Smith',
],
[
'id' => 3809,
'first_name' => 'Joe',
'last_name' => 'Doe',
],
];
// Extract the 'last_name' column
$lastNames = array_column($records, 'last_name');
print_r($lastNames);
Output:
Array
(
[0] => Griffin
[1] => Smith
[2] => Doe
)
In this example, array_column()
retrieves the ‘last_name’ values from each sub-array within $records
and returns them in a new array.
For more detailed information, you can refer to the official PHP documentation on array_column()
.