array_column() is an inbuilt PHP function which can be used to get the values from a single column from the given multi-dimensional array or an array of objects. Refer to the official documentation for same in manual

Syntax: array array_column ( array $input , mixed $column_key [, mixed $index_key = NULL ] )

Support: (PHP 5>=5.5.0, PHP 7)

Parameters for array_column():

$input:

The first parameter is necessary. It should be a multi-dimensional array or an array of objects from which to fetch/retrieve a column of values from. With an array of objects, public properties can be directly fetched. Whereas for protected or private properties, the class must implement both the __get() and __isset() methods.

$column_key

The second parameter is necessary. It should be the column key for which values are to be fetched from a multi-dimensional array or an array of objects. This value may be an integer key of the column you wish to retrieve, or it may be a string key name for an associative array or property name for an array of objects.

$index_key

The third parameter is optional. The column whose values are used as the index/keys for the returned/resulting array. This value may be the integer key of the column, or it may be the string key name.

Return Type:

The return type of array_column() function is another array.

array_column() function returns a 1-D array which contains values from a single column of the given array, which is identified by a column_key. Optionally, an index_key may also be provided to index the values in the resulted array by the values from the index_key column of the given array.

Example #1 Get the column of countries from a recordset

The above example will output:

Example #2 Get the column of capitals from a recordset, indexed by their respective “country” column

The above example will output:

Conclusion

A good programming technique is trying to avoid the use of loops, nested loops & callback functions. The array_column() helps to reduce the code complexity and increases the code readability.

Hope you find this helpful. If you have any issues or queries in code, let me know through comments.

LEAVE A REPLY

Please enter your comment!
Please enter your name here