PHP array_column function

P
PHP array_chunk() function
PHP array_combine() function

PHP array_column() function simply returns the values from the specified column of an associative array. Remind back the PHP associative arrays in which we have keys and values.

Considering the keys as the columns of the associative array, the array_column function is used to get the values of a single column (key) of the array.

What is the syntax of the array_column function in PHP?

array_column(array, column_key, index_key)
ParametersDetails
arrayRequired. Specify the associative array. You can also use objects from PHP 7.0
column_keyRequired. It can be a string or integer. When it’s an integer it specifies the index of the column to return its values. When it’s a string, it points towards the values of that key. It can also be NULL to reindex an indexed array.
index_keyOptional. The column to use as the index/keys for the resultant array
array_column function in PHP

Examples of array_column function

<?php
// An example array
$arr = array(
  array(
    'name' => Jawad,
    'gender' => 'Male',
    'age' => '24',
  ),
 array(
    'name' => Ahmad,
    'gender' => 'Male',
    'age' => '25',
  ),
 array(
    'name' => Sumerina,
    'gender' => 'Female',
    'age' => '39',
  ));

$ages = array_column($arr, 'age', 'name');
print_r($ages);
?>

In the above example, we fetch the age column values along with their names.

// Output
Array
(
  [Jawad] => 24
  [Ahmad] => 25
  [Sumerina] => 39
)
<?php
// An example array
$arr = array(
  array(
    'name' => Jawad,
    'gender' => 'Male',
    'age' => '24',
  ),
 array(
    'name' => Ahmad,
    'gender' => 'Male',
    'age' => '25',
  ),
 array(
    'name' => Sumerina,
    'gender' => 'Female',
    'age' => '39',
  ));

$names = array_column($arr, 'name');
print_r($names);
?>

In the above example, we fetch the names from the array only.

// Output
Array
(
  [0] => 24
  [1] => 25
  [2] => 39
)
PHP array_chunk() function
PHP array_combine() function

Add comment

Tutor Network

Share this

Learn PHP from A to Z