How to get an array of specific "key" in multidimensional array without looping
You can use the array_column
function to get an array of specific keys from a multidimensional array.
Here is an example:
<?php
$records = [
[
'id' => 2135,
'first_name' => 'John',
'last_name' => 'Doe',
],
[
'id' => 3245,
'first_name' => 'Sally',
'last_name' => 'Smith',
],
[
'id' => 5342,
'first_name' => 'Jane',
'last_name' => 'Jones',
],
[
'id' => 5623,
'first_name' => 'Peter',
'last_name' => 'Doe',
],
];
$ids = array_column($records, 'id');
print_r($ids);
The output of this code will be:
Array ( [0] => 2135 [1] => 3245 [2] => 5342 [3] => 5623 )
Watch a video course
Learn object oriented PHP
You can also specify a second argument to array_column
as the key of the array, and a third argument as the value. For example:
<?php
$records = [
[
'id' => 2135,
'first_name' => 'John',
'last_name' => 'Doe',
],
[
'id' => 3245,
'first_name' => 'Sally',
'last_name' => 'Smith',
],
[
'id' => 5342,
'first_name' => 'Jane',
'last_name' => 'Jones',
],
[
'id' => 5623,
'first_name' => 'Peter',
'last_name' => 'Doe',
],
];
$names = array_column($records, 'first_name', 'id');
print_r($names);
The output of this code will be:
Array ( [2135] => John [3245] => Sally [5342] => Jane [5623] => Peter )