Last Updated: November 19, 2020
·
6.443K
· 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

Have a fresh tip? Share with Coderwall community!

Post
Post a tip
Did you know?

PHP applications still send a browser full of JavaScript. Hardening the server does not inventory the payment, analytics, and plugin scripts that run after the HTML is delivered.

Security insights from Cside