PHP function array_column
is built in PHP function, that returns the values from a single column in the input array.
Basically, array_column()
return the single column of the array based on the column_key
provided by the program.
Parameters
array – A multi-dimensional array or an array of objects from which to take a column of values from.
column_key – Column key of the column to be returned. It may be a string key name for an associative array or property name.
index_key(optional) – The column to use as the index of the returned array.
Syntax
array_column(array, column_key, index_key)
Sample Code
<?php $customers = array( array( 'id' => 10, 'first_name' => 'John', 'last_name' => 'Doe', ), array( 'id' => 19, 'first_name' => 'Mark', 'last_name' => 'Spencer', ), array( 'id' => 50, 'first_name' => 'Jane', 'last_name' => 'Doe', ), array( 'id' => 100, 'first_name' => 'Peter', 'last_name' => 'Wick', ) ); $firstNames = array_column($customers, 'first_name'); print_r($firstNames); ?>
Output
Array ( [0] => John [1] => Mark [2] => Jane [3] => Peter )
To get the column of first names from with a index index
<?php $lastNames = array_column($customers, 'last_name', 'id'); print_r($lastNames); ?>
Output
Array ( [10] => Doe [19] => Spencer [50] => Doe [100] => Wick )
- Just want to thank us? Buy us a Coffee
- May be another day? Shop on Amazon using our links.
Your prices won't change but we get a small commission.
Leave a Reply