PHP array_column() Function

📆 Last updated Oct 31, 2019 👷 By, Chandan Tudu

What is the PHP array_column() Function?

The PHP array_column() function returns an array that contains specific column values of the given array.


Syntax of the array_column()

array_column(array, column_key, index_key);
  • The PHP array column function takes three parameters –
    1. array – An array.
    2. column_key – The column name or key which you want to return.
    3. index_key – It is an optional parameter. It is used to set a column value to the index key of the returning value.

Example:

In the following example, we separate specific column values from an array (this array represents a possible recordset returned from a database).

<?php
$users = array(
    array(
        'id' => 5211,
        'first_name' => 'John',
        'last_name' => 'Doe',
    ),
    array(
        'id' => 5421,
        'first_name' => 'Mark',
        'last_name' => 'Henry',
    ),
    array(
        'id' => 6523,
        'first_name' => 'Barry',
        'last_name' => 'Allen',
    ),
    array(
        'id' => 7541,
        'first_name' => 'Peter',
        'last_name' => 'Parker',
    )
);

$first_names = array_column($users,'first_name');

echo "<pre>";
var_dump($first_names);
echo "</pre>";
?>
Browser Output
array(4) {
  [0]=>
  string(4) "John"
  [1]=>
  string(4) "Mark"
  [2]=>
  string(5) "Barry"
  [3]=>
  string(5) "Peter"
}

index_key Parameter Example:

<?php
$users = array(
    array(
        'id' => 5211,
        'first_name' => 'John',
        'last_name' => 'Doe',
    ),
    array(
        'id' => 5421,
        'first_name' => 'Mark',
        'last_name' => 'Henry',
    ),
    array(
        'id' => 6523,
        'first_name' => 'Barry',
        'last_name' => 'Allen',
    ),
    array(
        'id' => 7541,
        'first_name' => 'Peter',
        'last_name' => 'Parker',
    )
);

$first_names = array_column($users, 'first_name', 'id');

echo "<pre>";
var_dump($first_names);
echo "</pre>";
?>
Browser Output
array(4) {
  [5211]=>
  string(4) "John"
  [5421]=>
  string(4) "Mark"
  [6523]=>
  string(5) "Barry"
  [7541]=>
  string(5) "Peter"
}

Leave a Reply

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