• PHP Video Tutorials

PHP array_column() Function



Definition and Usage

The array_column() function returns the values from a single column of the input array and identified by the column_key.

Optionally, you can pass index_key to index the values in the returned array by the values from the index_key column of the input array.

Syntax

array array_column( array $input , mixed $column_key [, mixed $index_key = NULL ] )

Parameters

Sr.No Parameter & Description
1

input (mandatory)

A multi-dimensional array or an array of objects from which to pull a column of values from.

2

column_key (mandatory)

The column of values to return. This value may be an integer key of the column you wish to retrieve, or it may be a string key name for an associative array or property name. This value can be NULL to return complete arrays or objects

3

index_key (optional)

The column to use as the index/keys for the returned array. This value may be the integer key of the column, or it may be the string key name.

Return Values

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

PHP Version

This function was first introduced in PHP Version 5.5.0. The the ability for the input parameter to be an array of objects was introduced in 7.0.0

Example

Try out following example to get the column of first names from a recordset −

<?php

 $records = array(
    array(
        'id' => 2135,
        'first_name' => 'Zara',
        'last_name' => 'Ali',
    ),
    array(
        'id' => 3245,
        'first_name' => 'Nuha',
        'last_name' => 'Mac',
    ),
    array(
        'id' => 5342,
        'first_name' => 'Shifa',
        'last_name' => 'Alam',
    ),
    array(
        'id' => 5623,
        'first_name' => 'Riya',
        'last_name' => 'Sweet',
    )
  );

 $first_names = array_column($records, 'first_name');
 print_r($first_names);
?>

This will produce following result −

Array
(
    [0] => Zara
    [1] => Nuha
    [2] => Shifa
    [3] => Riya
)

Example

Now let's try one more example to get the column of first names from a recordset but this time we will index recordset using id

<?php

 $records = array(
    array(
        'id' => 2135,
        'first_name' => 'Zara',
        'last_name' => 'Ali',
    ),
    array(
        'id' => 3245,
        'first_name' => 'Nuha',
        'last_name' => 'Mac',
    ),
    array(
        'id' => 5342,
        'first_name' => 'Shifa',
        'last_name' => 'Alam',
    ),
    array(
        'id' => 5623,
        'first_name' => 'Riya',
        'last_name' => 'Sweet',
    )
 );
 $first_names = array_column($records, 'first_name', 'id');
 print_r($first_names);
?>

This will produce following result −

Array
(
    [2135] => Zara
    [3245] => Nuha
    [5342] => Shifa
    [5623] => Riya
)
php_function_reference.htm
Advertisements