Curriculum
Course: PHP Basic
Login

Curriculum

PHP Basic

PHP Install

0/1

PHP Casting

0/1

PHP Constants

0/1

PHP Magic Constants

0/1

PHP Operators

0/1

PHP Reference

0/276
Text lesson

array_column()

Example

Retrieve the column of last names from a recordset:

<?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’);
print_r($last_names);
?>

Output:

Array
(
  [0] => Griffin
  [1] => Smith
  [2] => Doe
)

Definition and Usage

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

Syntax

array_column(array, column_key, index_key)

Parameter Values

Parameter

Description

array

Required. Specifies the multidimensional array (or record set) to use. Starting from PHP 7.0, this can also be an array of objects.

column_key

Required. An integer or string key representing the column of values to return. This parameter can also be NULL to return complete arrays, which is useful when used with index_key to re-index the array.

index_key

Optional. The column to use as the index or keys for the returned array.

Technical Details

Return Value:

Returns an array containing values from a single column of the input array.

PHP Version:

5.5+

More Examples

Example

Retrieve the column of last names from a recordset, using the “id” column as the index.

<?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
)