Php Array_Map Function
Suppose that you have an array that holds the lengths of squares:
1<?php
2
3$lengths = [10, 20, 30];
To calculate the areas of the squares, you may come up with the foreach loop like this:
1<?php
2
3$lengths = [10, 20, 30];
4
5// calculate areas
6$areas = [];
7
8foreach ($lengths as $length) {
9 $areas[] = $length * $length;
10}
11
12print_r($areas);
Output:
1Array
2(
3 [0] => 100
4 [1] => 400
5 [2] => 900
6)
Using array_map()
1<?php
2
3$lengths = [10, 20, 30];
4
5// calculate areas
6$areas = array_map(function ($length) {
7 return $length * $length;
8}, $lengths);
9
10
11print_r($areas);
See details in https://www.phptutorial.net/php-tutorial/php-array_map/