PHP array_column() Function

PHP array_column() function returns “the values from a single column in the input array.”

Syntax

array_column($array, $column_key, $index_key)

Parameters

$array(required):  A multi-dimensional array or an array of objects from which the column values will be extracted.

$column_key(required): The integer key or the string key name of the column of values to return. The column_key parameter can also be NULL to return the complete arrays.

$index_key(optional):  The column to use as the index/keys for the returned array.

Return value

The function returns an array that contains values from a single column of the input array, identified by a column_number.

Visual Representationvisual representation of PHP array_column() Function

Example 1: How to Use array_column() function 

<?php

$arr = array(
 array(
       'id' => 345,
       'name' => 'Ronaldo',
       'country' => 'Portugal',
      ),
 array(
       'id' => 122,
       'name' => 'Messi',
       'country' => 'Argentina',
      ),
 array(
       'id' => 756,
       'name' => 'Mbappe',
       'country' => 'France',
      ),
 array(
      'id' => 1222,
      'name' => 'Neymar',
      'country' => 'Brazil',
      )
);

 $result = array_column($arr, 'name');
 print_r($result);

Output

Array
(
 [0] => Ronaldo
 [1] => Messi
 [2] => Mbappe
 [3] => Neymar
)

In the above example, array_column() retrieved the ‘name‘ column from each array within the $arr array and returned it as a simple indexed array with the name.

Example 2: array_column() with index_keyVisual Representation of array_column() with index_key

<?php

$arr = array(
 array(
       'id' => 345,
       'name' => 'Ronaldo',
       'country' => 'Portugal',
      ),
 array(
       'id' => 122,
       'name' => 'Messi',
       'country' => 'Argentina',
      ),
 array(
       'id' => 756,
       'name' => 'Mbappe',
       'country' => 'France',
      ),
 array(
      'id' => 1222,
      'name' => 'Neymar',
      'country' => 'Brazil',
      )
);

 $result = array_column($arr, 'name','id');
 print_r($result);

Output

Array
(
 [345] => Ronaldo
 [122] => Messi
 [756] => Mbappe
 [1222] => Neymar
)

The output indicates that each id is used as the key for its corresponding name in the resulting array.

That’s it.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.