PHP array_column() Function

PHP array_column() Function

In this tutorial, we will learn how we can use the array_column() function to fetch the values from a single column in the input array.

In PHP, an array is a data structure that can hold an ordered list of values. It is a composite data type that allows you to store multiple values of the same data type under a single variable name.

Let us dive in.

Function Syntax

The following shows the syntax and definition for the array_function in PHP.

array_column(array $array, int|string|null $column_key, int|string|null $index_key = null): array

Function Parameters

The function accepts three main parameters:

  1. array - this defines the multidimensional array or array of objects from which to pull the column values.
  2. column_key - defines the column of values to return from the function. This can be an integer key of the column we wish to retrieve or a string key name for an associative array or property name.
  3. index_key - this defines the column to use as the index/keys for the returned array.

Function Return Value

The function returns an array of values representing a single column from the input array.

Examples

Let us look at a basic example on how to use the array_column() function.

$customers = array(
    array('id' => 1, 'first_name' => 'John', 'last_name' => 'Doe'),
    array('id' => 2, 'first_name' => 'Jane', 'last_name' => 'Smith'),
    array('id' => 3, 'first_name' => 'Bob', 'last_name' => 'Johnson')
);

$first_names = array_column($customers, 'first_name');
print_r($first_names);

This should return an output as shown:

Array
(
    [0] => John
    [1] => Jane
    [2] => Bob
)

Example 2

We can also fetch the column of the last names from the recordset indexed by the id column:

$last_names = array_column($customers, 'last_name', 'id');
print_r($first_names);

The resulting output is as shown:

Array
(
    [0] => John
    [1] => Jane
    [2] => Bob
)

Conclusion

In this post, we discussed how we can use the array_column() function to fetch the values froma single column in a given input array.

Table of Contents
Great! Next, complete checkout for full access to GeekBits.
Welcome back! You've successfully signed in.
You've successfully subscribed to GeekBits.
Success! Your account is fully activated, you now have access to all content.
Success! Your billing info has been updated.
Your billing was not updated.