array_column function in php 8.4

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, or null. If set to null, 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, or null. If not provided or set to null, 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().

Combining Multiple Columns into One Array using array_column() with PHP 8.4

You can also use array_column to extract values from multiple columns if you need them together. For example, let’s extract both the name and email fields into a new associative array.

<?php 
$namesAndEmails = array_map(function ($user) {
return [
'name' => $user['name'],
'email' => $user['email'],
];
},
$users);
print_r($namesAndEmails);
?>
<?phpArray
(
[name] => John
[email] => john@example.com
)
[1] => Array
(
[name] => Jane
[email] => jane@example.com
)
[2] => Array
(
[name] => Alice
[email] => alice@example.com
)
)
?>

In this case, we’re combining name and email into a new array, which requires array_map instead of array_column. You could use array_column for simpler tasks where only one column is needed.