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(
'name'=>'John Doe'
'name'=>'Merry Saw'
'name'=>'Smith Moe'
'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.

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

Related Articles

Comments 0