Using PHP array_map() Function: Syntax, Parameters, and Practical Examples
This article explains the PHP array_map() function, its signature and parameters, and demonstrates how to use it with both named and anonymous callbacks to transform arrays, such as converting strings to uppercase and doubling numeric values.
The array_map() function applies a user‑defined callback to each element of one or more arrays and returns a new array containing the transformed values.
Function signature
<code>array_map ( callable $callback , array $array1 [, array $... ] ) : array</code>Parameter description
$callback : The callback function that processes each element; it can be a named function or an anonymous function.
$array1 : The primary array to be processed.
$... : Optional additional arrays whose elements are passed to the callback.
Return value: A new array composed of the elements returned by the callback.
Example 1 – Using a named function
The following code defines a function convert_to_uppercase() that converts a string to uppercase, then uses array_map() to apply it to an array of names.
<code><?php
function convert_to_uppercase($value) {
return strtoupper($value);
}
$names = array("john", "james", "jane", "julie");
$names_uppercase = array_map("convert_to_uppercase", $names);
print_r($names_uppercase);
?></code>The script prints:
<code>Array
(
[0] => JOHN
[1] => JAMES
[2] => JANE
[3] => JULIE
)</code>Example 2 – Using an anonymous function
This example shows how to double each number in an array by passing an anonymous function to array_map() .
<code><?php
$numbers = array(1, 2, 3, 4, 5);
$doubled_numbers = array_map(function($value) {
return $value * 2;
}, $numbers);
print_r($doubled_numbers);
?></code>The output is:
<code>Array
(
[0] => 2
[1] => 4
[2] => 6
[3] => 8
[4] => 10
)</code>In real‑world development, array_map() is frequently used for array transformations, filtering, or any operation where each element needs to be processed by a custom callback.
php中文网 Courses
php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.