PHP array_map() Function
PHP array_map() Syntax
array_map(?callable $callback, array $array, array ...$arrays): array
PHP array_map() Basic examples
$nums = [1, 2, 3];
$result = array_map(fn($n) => $n * 2, $nums);
var_dump($result);
array(3) {
[0]=> int(2)
[1]=> int(4)
[2]=> int(6)
}
Transforms each array element.
PHP array_map() Real-world usage
$names = [" alice ", " bob "];
$clean = array_map('trim', $names);
var_dump($clean);
array(2) {
[0]=> string(5) "alice"
[1]=> string(3) "bob"
}
Cleans user input values.
PHP array_map() Edge cases
var_dump(array_map(null, [1,2], [3,4]));
array(2) {
[0]=> array(2) { [0]=> int(1) [1]=> int(3) }
[1]=> array(2) { [0]=> int(2) [1]=> int(4) }
}
Combines arrays when callback is null.
PHP array_map() Common mistakes
Using array_map for filtering
array_map does not remove elements.
array_map(fn($v) => $v > 2, [1,2,3]);
array_filter([1,2,3], fn($v) => $v > 2);
Use array_filter when removing elements.
PHP array_map() Frequently Asked Questions
What does array_map() do in PHP?
array_map() applies a callback function to each element of an array and returns a new array.
What is the syntax of array_map()?
array_map(callable $callback, array $array, array ...$arrays): array
Does array_map() modify the original array?
No, it returns a new array and leaves the original unchanged.
Can array_map() work with multiple arrays?
Yes, it can process multiple arrays in parallel.
What happens if arrays have different lengths?
Shorter arrays are padded with null values.
Can array_map() be used without a callback?
Yes, passing null returns arrays grouped by index.
Is array_map() faster than foreach?
Performance is similar; choice depends on readability and use case.
Can array_map() handle associative arrays?
Yes, but keys are preserved only with a single array.
What is a real-world use case of array_map()?
Transforming data such as trimming, formatting, or mapping values.
Can array_map() return different data types?
Yes, the callback can return any type.
Is array_map() functional programming?
Yes, it is a functional-style approach to processing arrays.
Can array_map() be combined with other functions?
Yes, it is often used with array_filter() or array_reduce().
PHP array_map() Related PHP Functions
-
array_allLearn more about array_all
-
array_anyLearn more about array_any
-
array_change_key_caseLearn more about array_change_key_case
-
array_chunkLearn more about array_chunk
-
array_filter PHP examplesLearn more about array_filter PHP examples
-
array_walk PHP examplesLearn more about array_walk PHP examples