array_column(array, column_name) is another very powerful function available in PHP. It allows to extract all the values from the specified column from a multi-dimensional array without looping into each one of the nested arrays. These are the most common ways to implement this function:
Option 1. With a multi-dimensional array:
$persons = [
[
'id' => 50001,
'first_name' => 'John',
'last_name' => 'Doe',
],
[
'id' => 31245,
'first_name' => 'Sally',
'last_name' => 'Smith',
],
[
'id' => 53642,
'first_name' => 'Jane',
'last_name' => 'Jones',
],
[
'id' => 56213,
'first_name' => 'Peter',
'last_name' => 'Doe',
]
];
$result = array_column($persons, 'last_name');
This will output:
Array
(
[0] => Doe
[1] => Smith
[2] => Jones
[3] => Doe
)
Option 2. Specify a key from the nested arrays as the key for each one of the values extracted:
$persons = [
[
'id' => 50001,
'first_name' => 'John',
'last_name' => 'Doe',
],
[
'id' => 31245,
'first_name' => 'Sally',
'last_name' => 'Smith',
],
[
'id' => 53642,
'first_name' => 'Jane',
'last_name' => 'Jones',
],
[
'id' => 56213,
'first_name' => 'Peter',
'last_name' => 'Doe',
]
];
$result = array_column($persons, 'last_name' , 'id');
This will output:
Array
(
[50001] => Doe
[31245] => Smith
[53642] => Jones
[56213] => Doe
)
Option 3. Get the values of a given property in a array of DTOs (refer to Using DTOs in PHP Symfony, How to validate input data in Symfony using DTOs for more info on these data structures):
class userDto
{
/**
* @var int
*/
public int $id;
/**
* @var string
*/
public string $firstName;
/**
* @var string
*/
public string $lastName;
}
$user_1 = new userDto();
$user_1->id = 101010;
$user_1->firstName ='Sally';
$user_1->lastName = 'Smith';
$user_2 = new userDto();
$user_2->id = 202020;
$user_2->firstName ='John';
$user_2->lastName = 'Doe';
$user_3 = new userDto();
$user_3->id = 303030;
$user_3->firstName ='Peter';
$user_3->lastName = 'Doe';
$persons = [
$user_1,
$user_2,
$user_3
];
$result = array_column($persons, 'firstName' , 'id');
This will output:
Array
(
[101010] => Sally
[202020] => John
[303030] => Peter
)