Bladephp: Now with 7+ codeigniter, php, and laravel project 7+ php project From $18/Year From Rs. 1000/Year

PHP array_column() Function

by
Category:php
php php array function
PHP array_column() Function

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

array_column() returns the values from a single column of the array, identified by the column_key. Optionally, an index_key may be provided to index the values in the returned array by the values from the index_key column of the array.

Parameter Description
array A multi-dimensional array or an array of objects from which to pull a column of values from.
column_key Required. An integer key or a string key name of the column of values to return.
index_key Optional. The column to use as the index/keys for the returned array. This value may be the integer key of the column, or it may be the string key name.

Example

$array = array(
  array(
    'id' => 101,
    'first_name' => 'Prince',
    'nick_name' => 'Alex',
  ),
  array(
    'id' => 102,
    'first_name' => 'James',
    'nick_name' => 'Lachlan',
  ),
  array(
    'id' => 103,
    'first_name' => 'Samuel',
    'nick_name' => 'Cooper',
  )
);

$nick_names = array_column($array, 'nick_name');
print_r($nick_names);

Output

Array ( 
      [0] => Alex 
      [1] => Lachlan 
      [2] => Cooper 
    ) 

More Example key and value

$array = array(
  array(
    'id' => 101,
    'first_name' => 'Prince',
    'nick_name' => 'Alex',
  ),
  array(
    'id' => 102,
    'first_name' => 'James',
    'nick_name' => 'Lachlan',
  ),
  array(
    'id' => 103,
    'first_name' => 'Samuel',
    'nick_name' => 'Cooper',
  )
);

$nick_names = array_column($array, 'nick_name', 'id');
print_r($nick_names);

Output

Array ( 
      [101] => Alex 
      [102] => Lachlan 
      [103] => Cooper 
     ) 

In above examplle, get column of nick_name from a recordset, indexed by the "id" column.


0 Comments


Html code work in comment box


Related Post