Blog

If you have a large set of multidimensional array and you tortured to without help profit array of specific key for multidimensional array in PHP, After general pardon of php 5.5+ These is predefined take steps 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 realize multidimensional array result and you and no-one else twinge agreed column auditorium from array later this easy function condense your effort and in addition to 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 sore spot to gate all the citys from $companyArr array and create an array of cities. The once single heritage of code will realize it easily.

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

Another example to realize all the company names array isolated by array_column

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

Leave a Reply

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