PHP array_column() Function

Usage

The array_column() function returns the values from a single column in the input array.

Syntax

array_column(array,column_key,index_key);

array: Required. Specifies the multi-dimensional array (record-set) to use

column_key: Required. An integer key or a string key name of the column of values to return. This parameter can also be NULL to return complete arrays (useful together with index_key to re-index the array)

index_key : Optional. The column to use as the index/keys for the returned array

Example :

<?php
// An array that represents a possible record set returned from a database
$a = array(
  array(
    'id' => 5698,
    'first_name' => 'Peter',
    'last_name' => 'Griffin',
  ),
  array(
    'id' => 4767,
    'first_name' => 'Ben',
    'last_name' => 'Smith',
  ),
  array(
    'id' => 3809,
    'first_name' => 'Joe',
    'last_name' => 'Doe',
  )
);
$last_names = array_column($a, 'last_name', 'id');
print_r($last_names);
?>

Output :

Array
(
  [5698] => Griffin
  [4767] => Smith
  [3809] => Doe
)

Leave a Comment

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