array_column() is an another PHP prebuilt / default array function, This function is basically allows user to get the values from a single column in the input array identified by the column_key.
Syntax of array_column() :
array_column(array, column_key, index_key)
Parameter :
– array (required) : multi-dimensional array (record-set) to use. in latest PHP this can also be an array of objects.
– column_key (required) : An integer key/string key name of the column of values to return. This parameter can also be NULL to return complete arrays.
– index_key (optional) : The column to use as the index/keys for the returned array.
Return Type / Values :
Returns an array of values that represents a single column from the input array.
Example 1 : By using the array_column() getting column of last names from a record set :
<?php $user_details = array( array( 'userId' => 1, 'first_name' => 'Sonu', 'last_name' => 'Singh', ), array( 'userId' => 2, 'first_name' => 'Abhishek', 'last_name' => 'Tiwari', ), array( 'userId' => 3, 'first_name' => 'Parth', 'last_name' => 'Pandey', ) ); $user_last_names = array_column($user_details, 'last_name'); print_r($user_last_names); ?>
Output will be :
Array ( [0] => Singh [1] => Tiwari [2] => Pandey )
Example 2 : Get column of last names from a record set, indexed by the “userId” column:
<?php $user_details = array( array( 'userId' => 8676, 'first_name' => 'Sonu', 'last_name' => 'Singh', ), array( 'userId' => 2340, 'first_name' => 'Abhishek', 'last_name' => 'Tiwari', ), array( 'userId' => 2142, 'first_name' => 'Parth', 'last_name' => 'Pandey', ) ); $user_last_names = array_column($user_details, 'last_name', 'userId'); print_r($user_last_names); ?>
Output will be :
Array ( [8676] => Singh [2340] => Tiwari [2142] => Pandey )
Reference Article : https://www.php.net/manual/en/function.array-column.php
In the previous post I described regarding the PHP array_column Function
Hope this article helps you in PHP development and understandings of Array. Stay tuned for more PHP Tutorials, Hope you enjoyed reading, if you need the professional PHP, PHP Framework and Magento 2 Development we can help you, just Click on the Link and send me your requirements.