This is an old revision of the document!
Request for Comments: array_column
- Version: 1.0
- Date: 2012-06-21
- Author: Ben Ramsey ramsey@php.net
- Status: Under Discussion
- First Published at: http://wiki.php.net/rfc/array_column
Introduction
This RFC proposes a new array function that returns the values of the specified column from a multi-dimensional array. Inspired by database methods like PDOStatement::fetchColumn()
, array_column()
moves useful functionality into the core that once had to be implemented in userland code with sometimes complex loops.
This has been submitted as a pull request on GitHub, where there has already been a significant amount of discussion.
Specification
Description
array array_column(array $input, mixed $key)
array_column()
returns the values from a single column of the input array, identified by the key.
Parameters
input
A multi-dimensional array (record set) from which to pull a column of values.
key
The column of values to return. This value may be the 0-indexed number of the column you wish to retrieve, or it may be the string key name for an associative array.
Return Values
Returns an array of values representing a single column from the input array.
Examples
Example #1: Get column of first names from recordset
<?php // Array representing a possible record set returned from a database $records = array( array( 'id' => 1, 'first_name' => 'John', 'last_name' => 'Doe' ), array( 'id' => 2, 'first_name' => 'Sally', 'last_name' => 'Smith' ), array( 'id' => 3, 'first_name' => 'Jane', 'last_name' => 'Jones' ) ); $firstNames = array_column($records, 'first_name'); print_r($firstNames);
The above example will output:
Array ( [0] => John [1] => Sally [2] => Jane )
Example #2: Retrieve a column of values from a numerically-indexed array
<?php $records = array( array(1, 'John', 'Doe'), array(2, 'Sally', 'Smith'), array(3, 'Jane', 'Jones') ); $lastNames = array_column($records, 2); print_r($lastNames);
The above example will output:
Array ( [0] => Doe [1] => Smith [2] => Jones )
Proposal and Patch
The patch (including tests) for this proposal is available in GitHub Pull Request #56.
Changelog
- 1.0 (2012-06-21): Initial draft, following discussion on on GitHub Pull Request #56