PHP array_column() Function

Last Updated on July 28, 2021 by Roshan Parihar

PHP array_column() Function is used to return the values for the single column in the input array. You have to specify the column from where you have to fetch the values in the output.

Syntax of PHP array_column() Function

array_column(array, column_key, index_key)

The function takes three arguments which the first argument is the array from which you want to get the column values. The second argument is the column name to fetch the record from the array. The third is the index key.

Description of Parameters

Name Description
array Required. It is the array that you have to use and return the values for the single column.
column_key Required. Specify the single string or numeric column key to return its values. It can also be a NULL value that returns the complete array
index_key optional. It is the index key to specify that can be a string or numeric. It is optional to use with the function.

Let’s see some examples that are useful to understand the use of the PHP array_column() Function in PHP.

Examples of PHP array_column() Function

See the example given below to learn the use of the function to return value for the single specified column name.

Example 1: Return Values for the First Column in an Input Array

To return the values of the first column in an input array, you have to use the PHP array_column() Function and pass two arguments to it. The first argument is the array and the second argument is the column name to get its values.

Output

Array ( [0] => 2 [1] => 13 [2] => 4 )

The above example contains three subarrays. The function returns the first value from all three subarrays.

Example 2: Get Second Column Values

Similarly, to get the value of the second column, you have to pass the second column name as the second argument of the function. The first argument will be the same that is the array or the array variable to pass.

Output

Array ( [0] => 5 [1] => 21 [2] => 10 )

The output in the above example is the array that is created by using all the values of the second column.

Example 3: Print Third Column Values in an input Array

In addition to the above methods, you can also get all the values of the third column for the input array. You have to pass the third column name as the second argument of the PHP array_column() function.

Output

Array ( [0] => 9 [1] => 33 [2] => 19 )

The above example contains the array created by using all the second column values from the subarrays of the given array in PHP.

You May Also Like to Read

Leave a comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.