Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / PHP

Reductions and statistics

Reduce a sequence by passing the previous accumulator and the current value to a callback.

Version: PHP 8.4; repository runtime, production runtime not attested

Syntax

array_reduce($values, $combine, $initial);

Reduce a sequence by passing the previous accumulator and the current value to a callback. For a mean, carry both sum and count and divide only after the traversal. An explicit initial pair handles empty input predictably. A mean with zero observations must be handled before division.

function mean(array $xs):?float{[$s,$n]=array_reduce($xs,fn($a,$v)=>[$a[0]+$v,$a[1]+1],[0,0]);return $n===0?null:$s/$n;}echo json_encode([mean([2,3,5]),mean([])],JSON_PRESERVE_ZERO_FRACTION);
[3.3333333333333335,null]

Examples

<?php
function mean(array $xs):?float{[$s,$n]=array_reduce($xs,fn($a,$v)=>[$a[0]+$v,$a[1]+1],[0,0]);return $n===0?null:$s/$n;}echo json_encode([mean([2,3,5]),mean([])],JSON_PRESERVE_ZERO_FRACTION);

Result

[3.3333333333333335,null]

Sources