Using PHP’s array_map() Function: Syntax, Parameters, and Practical Examples
This article explains PHP’s array_map() function, detailing its syntax, parameters, and return value, and provides clear examples using both named and anonymous callback functions to transform arrays, such as converting strings to uppercase and doubling numeric values.
PHP, as a widely used programming language, offers many built-in functions to simplify various operations. One particularly useful function is array_map() , which applies a callback to each element of one or more arrays and returns a new array.
array_map() Function Usage
<code>array_map ( callable $callback , array $array1 [, array $... ] ) : array</code>Parameter Description
$callback : The callback function that processes each array element. It can be a defined function or an anonymous function.
$array1 : The array to be processed.
$... : Optional additional arrays.
Return value: A new array containing the elements after the callback has been applied.
Usage Example
The following simple example shows how to use array_map() to convert each element of an array to uppercase:
<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 code defines a function convert_to_uppercase() that returns the uppercase version of a given value, creates an array $names with lowercase names, and then uses array_map() to apply the function to each name, storing the results in $names_uppercase . The output is:
<code>Array
(
[0] => JOHN
[1] => JAMES
[2] => JANE
[3] => JULIE
)</code>Besides using a predefined function as the callback, an anonymous function can also be used. The following example doubles each element of an array:
<code><?php
$numbers = array(1, 2, 3, 4, 5);
$doubled_numbers = array_map(function($value) {
return $value * 2;
}, $numbers);
print_r($doubled_numbers);
?></code>This code passes an anonymous function to array_map() that returns the value multiplied by two. The resulting array $doubled_numbers is printed, producing:
<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 other operations. By providing different callbacks, developers can apply a wide range of manipulations to each element, simplifying code and improving efficiency.
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.