What is the array_column() method in PHP?

Overview

In PHP, we can use the array_column() method to create a column from a multidimensional array. It will return a single column from an array identified by the column’s key. We may also specify which keys will be used as an index for the new array to be returned.

Syntax

array_column($arrayVal,$columnKey, $indexKey)

Parameters

  • $arrayVal: This is a multi-dimensional array or an array that contains object values. A single column will be targeted in this array, and the column’s values in each sub-arrays will be returned.

  • columnKey: The column’s key is targeted in the $arrayVal. It can be an integer key or a string key of the column to be returned. In the case of an object, it will be a property name. Providing a null value here will cause all of the array values to be returned, but you may re-index this new array using this function’s third parameter explained below.

  • indexKey: This is a column key of the sub-arrays in $arrayVal, whose value will be used as the new index value of the column to be retrieved from the array.

Return value

The array_column method will return an array with values as the retrieved column and possibly an index that is another column’s value in the targeted array.

Example

The snippet below will return the column values of the multidimensional $products array.

<?php
// Array representing a possible record set returned from a database
$products = array(
array(
'id' => 5,
'price' => 5167,
'name' => 'watch',
),
array(
'id' => 6,
'price' => 349,
'name' => 'chairs',
),
array(
'id' => 7,
'price' => '788',
'name' => 'peanut',
),
array(
'id' => 8,
'price' => 348,
'name' => 'snacks',
)
);
//get the prices column
$prices = array_column($products , 'price');
print_r($prices);
// get the product names columns
$name = array_column($products, 'name','id');
print_r($name);
?>

Explanation

Below is an explanation of the code in the code widget above.

  • Lines 3–24: We’ll declare a multidimensional array with values from which columns can be created.

  • Line 27: We use the array_column() method to create a column from the price values of the $products array.

  • Line 28: We print the column, which is an array.

  • Line 31: The array_column() method creates a column from the name values of all the nested arrays and the id values used as the index keys.

  • Line 32: We’ll display the return value.

Free Resources