1
2 <?php
3function my_callback($item) {
4 return strlen($item);
5}
6
7
8 $strings = ["apple", "orange",
9 "banana", "coconut"];
10$lengths =
11 array_map("my_callback", $strings);
12print_r($lengths);
13?>
1The array_map() function sends each value of an array to a user-made function, and returns an array with new values, given by the user-made function.
2
3Tip: You can assign one array to the function, or as many as you like.
4
5Syntax
6array_map(functionname, array1, array2, array3, ...)
7
8Example
9Send each value of an array to a function, multiply each value by itself, and return an array with the new values:
10
11<?php
12function myfunction($val)
13{
14 return($val*$val);
15}
16
17$a=array(1,2,3,4,5);
18print_r(array_map("myfunction",$a));
19?>
1Array
2(
3 [0] => Array
4 (
5 [1] => Hamza
6 [1] => Hamza
7 [1] => Hamza
8 [1] => Hamza
9 [1] => Hamza
10 )
11
12 [1] => Array
13 (
14 [2] => Bilal
15 )
16
17 [2] => Array
18 (
19 [3] => Asad
20 )
21
22 [3] => Array
23 (
24 [4] => Asif Bhai
25 )
26
27 [4] => Array
28 (
29 [5] => Waqas
30 )
31
32 [5] => Array
33 (
34 [6] => Umair
35 )
36
37)
38