How to Get an Array of Specific Key from Multidimensional Array


Code optimization can reduce the execution time of the script. If you want to make your web application faster, write code in a smart way. This example will show how can you replace multiple lines of code with a single line code.

Using the looping statements, you can get an array of a specific key from the multidimensional array. But the same work can be done in a single line of code by array_column() function in PHP.

Multidimensional Array:

$users = array(
    array(
        
'id'=>123,
        
'name'=>'John Doe'
    
),
    array(
        
'id'=>456,
        
'name'=>'Merry Saw'
    
),
    array(
        
'id'=>789,
        
'name'=>'Smith Moe'
    
),
    array(
        
'id'=>147,
        
'name'=>'Chris Tang'
    
)
);

Now you want to retrieve all the IDs from $users array and create an array of id value. The following single line of code will do it easily.

$ids array_column($users'id');

The above code will return an array that contains the values of the specific key.

Array
(
    [0] => 123
    [1] => 456
    [2] => 789
    [3] => 147
)

Leave a reply