Understanding PHP's array_map() Function: Syntax, Examples, and Best Practices
This article introduces PHP's array_map() function, explains its syntax, demonstrates multiple practical examples such as doubling values, merging arrays, and removing empty elements, and outlines important usage considerations to help backend developers efficiently manipulate arrays.
In PHP development, arrays are frequently used, and the array_map() function is a powerful tool that applies a callback to each element of an array and returns a new array.
This article explains the definition, syntax, and usage of array_map() , and provides several illustrative examples.
1. array_map() Function Overview
The function takes a callable as the first argument and one or more arrays as subsequent arguments. It applies the callable to each element and returns an array of the results.
Basic syntax:
<code>array array_map ( callable $callback , array $array1 [, array $...] )</code>The $callback parameter is the function to apply, and $array1 is the array to process. Multiple arrays can be supplied, allowing the callback to receive multiple parameters.
2. array_map() Examples
Doubling all elements in an array
<code><?php
function double($value){
return $value*2;
}
$a = array(1, 2, 3, 4, 5);
$b = array_map("double", $a);
print_r($b);
?></code>Output:
<code>Array ( [0] => 2 [1] => 4 [2] => 6 [3] => 8 [4] => 10 )</code>Merging two arrays element‑wise
<code><?php
function combine($a, $b){
return $a . $b;
}
$a = array("a", "b", "c", "d");
$b = array("1", "2", "3", "4");
$combine = array_map("combine", $a, $b);
print_r($combine);
?></code>Output:
<code>Array ( [0] => a1 [1] => b2 [2] => c3 [3] => d4 )</code>Removing empty elements from an array
<code><?php
function removeEmpty($value){
return trim($value);
}
$array = array("hello", " ", "world", "", "!");
$no_empty = array_filter(array_map("removeEmpty", $array));
var_dump($no_empty);
?></code>Output:
<code>array(3) { [0]=> string(5) "hello" [2]=> string(5) "world" [4]=> string(1) "!" }</code>3. Important Considerations
When using array_map() , remember that the callback receives the current element value, and the function is sensitive to array indexes. If you need both keys and values, or more complex handling, a foreach loop may be more appropriate.
4. Summary
The article covered the definition, syntax, practical examples, and best‑practice tips for PHP's array_map() function. By applying a callback to each array element, developers can efficiently transform data and simplify array manipulation in backend applications.
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.