How to get array of specific key for multidimensional array in PHP

If you have a large set of multidimensional array and you want to only get array of specific key for multidimensional array using PHP, After release of php 5.5+ These is predefined function called array_column. It Return the values from a single column in the input array. Like you have write a query to fetch data from database get multidimensional array result and you only want selected column field from array then this simple function reduce your effort and also helpful to optimize your code.



Sample multidimensional array:

$companyArr = array(
     array(
         'id'=>1,
         'name'=>'HCL',
         'city'=>'Noida'
     ),
     array(
         'id'=>1,
         'name'=>'Infosys',
         'city'=>'Bangalore'
     ),
     array(
         'id'=>1,
         'name'=>'Wipro',
         'city'=>'Gurgaon'
     )
);

Now you want to retrieve all the city’s from $companyArr array and create an array of cities. The following single line of code will do it easily.

$cities = array_column($companyArr, 'city');
/*
OUTPUT:
Array
(
    [0] => Noida
    [1] => Bangalore
    [2] => Gurgaon
)
*/

Another example to get all the company names array only by array_column

$companyNames = array_column($companyArr, 'name');
/*
OUTPUT:
Array
(
    [0] => HCL
    [1] => Infosys
    [2] => Wipro
)
*/



Posted in: PHP

2 Replies to “How to get array of specific key for multidimensional array in PHP”

  1. Hi rohit,

    I want to tutorial about json php data insert into database & update this json data by perticular id of json data so plz help me about this.

Leave a Reply

Your email address will not be published. Required fields are marked *

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