array_column() Function Use In PHP 8.1 & PHP 8.2 With Example

Support PHP Version: PHP 7.1, PHP 7.2, PHP 7.3, PHP 7.4, PHP 8.0, PHP 8.1, PHP 8.2, PHP 8.3 With Latest All Version Support.

The `array_column()` function in PHP is used to return the values from a single column in the input array. It is especially useful when dealing with arrays of associative arrays or objects.

Here’s the syntax for `array_column()`:

<?php
array_column(array $input, string|int|null $column_key, string|int|null $index_key = null): array
?>

– `$input`: The multi-dimensional array (typically an array of arrays or an array of objects).
– `$column_key`: The column of values to return. This value may be an integer key or a string key name.
– `$index_key`: (Optional) The column to use as the index/keys for the returned array.

Example of `array_column()` in PHP

Let’s assume we have an array of associative arrays representing a list of users, and we want to extract a list of their email addresses.

<?php
$users = [
[
"id" => 1,
"name" => "John Doe",
"email" => "john@example.com",
],
[
"id" => 2,
"name" => "Jane Smith",
"email" => "jane@example.com",
],
[
"id" => 3,
"name" => "Sam Brown",
"email" => "sam@example.com",
],
];
$emails = array_column($users, 'email');
print_r($emails);
?>

Output:

<?php
Array
(
[0] => john@example.com
[1] => jane@example.com
[2] => sam@example.com
)
?>

In this example, `array_column()` extracts the ’email’ values from the `$users` array and returns them in a new array.

Using the `index_key` parameter

We can also specify a key to use as the indexes for the returned array. For example, if we want the user IDs to be the keys of the returned array, we can do this:

<?php
$emails_with_ids = array_column($users, 'email', 'id');
print_r($emails_with_ids);
?>

Output:

<?php
Array
(
[1] => john@example.com
[2] => jane@example.com
[3] => sam@example.com
)
?>

Here, the returned array has user IDs as keys and their email addresses as values.

These examples demonstrate how `array_column()` can be effectively used in PHP to manipulate and extract data from multi-dimensional arrays.