array_map
array_map(?callable $callback, array $array, array ...$arrays): array
Applies a callback to every element of an array and returns a new array.
C C23
C23
#include <stdio.h>
int main(void) {
int xs[] = {1, 2, 3};
size_t n = sizeof xs / sizeof xs[0];
int out[3];
for (size_t i = 0; i < n; i++) { // hand-written map: C has no map-style higher-order function
out[i] = xs[i] * 2;
}
printf("[");
for (size_t i = 0; i < n; i++) {
printf(i ? ", %d" : "%d", out[i]);
}
printf("]\n");
return 0;
}
Output
[2, 4, 6]
C++ C++26
C++26
#include <algorithm>
#include <iostream>
#include <iterator>
#include <vector>
int main() {
std::vector<int> xs = {1, 2, 3};
std::vector<int> doubled;
std::transform(xs.begin(), xs.end(), std::back_inserter(doubled),
[](int x) { return x * 2; }); // lambda applied to each element
std::cout << "[";
for (size_t i = 0; i < doubled.size(); ++i) {
if (i) std::cout << ", ";
std::cout << doubled[i];
}
std::cout << "]\n";
return 0;
}
Output
[2, 4, 6]
C# v11.0.100
v11.0.100
var xs = new List<int> { 1, 2, 3 };
var doubled = xs.Select(x => x * 2).ToList();
Console.WriteLine($"[{string.Join(", ", doubled)}]");
Output
[2, 4, 6]
Go v1.27.4
v1.27.4
package main
import "fmt"
func main() {
a := []int{1, 2, 3}
b := make([]int, len(a))
for i, v := range a {
b[i] = v * 2
}
fmt.Println(b)
}
Output
[2 4 6]
Java v27.0.1
v27.0.1
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
System.out.println(Arrays.toString(Arrays.stream(new int[]{1, 2, 3}).map(x -> x * 2).toArray()));
}
}
Output
[2, 4, 6]
JavaScript v26.13.1
v26.13.1
console.log([1, 2, 3].map(x => x * 2))
Output
[ 2, 4, 6 ]
PHP v8.6.0
v8.6.0
echo json_encode(array_map(fn($x) => $x * 2, [1, 2, 3]));
Output
[2,4,6]
Python v3.15.2
v3.15.2
print(list(map(lambda x: x * 2, [1, 2, 3])))
Output
[2, 4, 6]
Rust v1.99.1
v1.99.1
fn main() {
let v: Vec<i32> = vec![1, 2, 3].iter().map(|x| x * 2).collect();
println!("{:?}", v);
}
Output
[2, 4, 6]
TypeScript v26.13.1
v26.13.1
const xs: number[] = [1, 2, 3];
console.log(xs.map((x) => x * 2));
Output
[ 2, 4, 6 ]
Language differences
C: has no built-in containers or higher-order functions; the example uses fixed arrays/buffers and hand-written loops.
C++: maps with std::transform plus a lambda.
C#: maps with LINQ Select; the result is a lazy IEnumerable<T> usually collected with ToList().
Go: no built-in, needs a hand-written loop.
Java: uses Stream.map.
JavaScript: arrays have a built-in map.
Python: map returns a lazy iterator that must be collected with list().
Rust: iter().map() returns a lazy iterator that must be collected with collect().