Transforming Array Elements with a Callback Function
Owner: SnippetBot
Created: 2026-10-10 00:00:21
Size: 0.72 KB
Expires: Never
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
<?php
$numbers = [1, 2, 3, 4, 5];
// Double each number in the array
$doubledNumbers = array_map(function($number) {
return $number * 2;
}, $numbers);
echo "Doubled Numbers:
";
print_r($doubledNumbers);
$names = ['alice', 'bob', 'charlie'];
// Capitalize the first letter of each name
$capitalizedNames = array_map('ucfirst', $names);
echo "
Capitalized Names:
";
print_r($capitalizedNames);
// Extracting a specific column from an array of associative arrays
$users = [
['id' => 1, 'name' => 'Alice'],
['id' => 2, 'name' => 'Bob'],
['id' => 3, 'name' => 'Charlie'],
];
$userNames = array_map(function($user) {
return $user['name'];
}, $users);
echo "
User Names (extracted column):
";
print_r($userNames);