array_reduce

array_reduce(array $array, callable $callback, mixed $initial = null): mixed

Reduces an array to a single value using a callback.

C C23

C23
#include <stdio.h>
int main(void) {
    int xs[] = {1, 2, 3, 4};
    size_t n = sizeof xs / sizeof xs[0];
    int carry = 0; // accumulator: hand-written fold, C has no reduce-style higher-order function
    for (size_t i = 0; i < n; i++) {
        carry += xs[i];
    }
    printf("%d\n", carry);
    return 0;
}
Output
10

C++ C++26

C++26
#include <iostream>
#include <numeric>
#include <vector>
int main() {
    std::vector<int> xs = {1, 2, 3, 4};
    // std::accumulate folds the sequence; the initial value 0 determines the result type
    std::cout << std::accumulate(xs.begin(), xs.end(), 0) << "\n";
    return 0;
}
Output
10

C# v11.0.100

v11.0.100
var xs = new List<int> { 1, 2, 3, 4 };
// Aggregate: folds the sequence from a seed value, equivalent to array_reduce
Console.WriteLine(xs.Aggregate(0, (carry, item) => carry + item));
Output
10

Go v1.27.4

v1.27.4
package main

import "fmt"

func main() {
    a := []int{1, 2, 3, 4}
    sum := 0
    for _, v := range a {
        sum += v
    }
    fmt.Println(sum)
}
Output
10

Java v27.0.1

v27.0.1
import java.util.Arrays;

public class Main {
    public static void main(String[] args) {
        System.out.println(Arrays.stream(new int[]{1, 2, 3, 4}).reduce(0, (a, b) -> a + b));
    }
}
Output
10

JavaScript v26.13.1

v26.13.1
console.log([1, 2, 3, 4].reduce((a, b) => a + b, 0))
Output
10

PHP v8.6.0

v8.6.0
echo array_reduce([1, 2, 3, 4], fn($carry, $item) => $carry + $item, 0);
Output
10

Python v3.15.2

v3.15.2
from functools import reduce

print(reduce(lambda a, b: a + b, [1, 2, 3, 4], 0))
Output
10

Rust v1.99.1

v1.99.1
fn main() {
    let v = vec![1, 2, 3, 4];
    println!("{}", v.iter().fold(0, |acc, x| acc + x));
}
Output
10

TypeScript v26.13.1

v26.13.1
const xs: number[] = [1, 2, 3, 4];
console.log(xs.reduce((carry, item) => carry + item, 0));
Output
10

Language differences

C: has no built-in containers or higher-order functions; the example uses fixed arrays/buffers and hand-written loops.

C++: folds a sequence with std::accumulate.

Go: no built-in reduce, use a loop.

Java: uses Stream.reduce.

JavaScript: arrays have a built-in reduce.

Python: reduce must be imported from functools (for simple sums the built-in sum works).

Rust: uses fold.