Last Updated: November 19, 2020
·
5.843K
· rfsbsb

List Comprehension in PHP

Often you need to extract some data from arrays. In Python it's usually done by using list comprehensions. Sadly PHP doesn't have this structure, but it can be achieved using the array_map function like the example below:

<?php
$data = $multi_dimensional_array;
$extracted_info =  array_map(function($a) {return $a['second_dimension']['third_dimension'];}, $data);
?>

Using this code you will have all the values from third dimension item as an array in $extracted_info variable.

Related protips:

Flatten a list of lists in one line in Python