3v4l.org

run code in 300+ PHP versions simultaneously
<?php /** * `$pred`が`true`を返す要素だけを抽出 */ function filter(callable $pred): Closure { return function (iterable $it) use ($pred): Generator { foreach ($it as $k => $v) { if ($pred($v, $k)) yield $k => $v; } }; } /** * `$f`を各要素に適用した結果を返す */ function map(callable $f): Closure { return function (iterable $it) use ($f): Generator { foreach ($it as $k => $v) { yield $k => $f($v, $k); } }; } /** * 副作用を実行し、値はそのまま次へ */ function tap(callable $side): Closure { return function (iterable $it) use ($side): Generator { foreach ($it as $k => $v) { $side($v, $k); yield $k => $v; } }; } /** * `$f`を使って要素を累積的に処理し、最終結果を返す */ function reduce(callable $f, mixed $initial = null): Closure { return function (iterable $it) use ($f, $initial) { $acc = $initial; foreach ($it as $v) { $acc = $f($acc, $v); } return $acc; }; } // ダミーデータ $orders = [ ['id' => 101, 'status' => 'paid', 'total' => 1200], ['id' => 102, 'status' => 'cancelled', 'total' => 800], ['id' => 103, 'status' => 'paid', 'total' => 1500], ['id' => 104, 'status' => 'pending', 'total' => 600], ['id' => 105, 'status' => 'paid', 'total' => 900], ]; $paidCount = 0; $bigOrders = []; $sum = $orders |> filter(fn($o) => $o['status'] === 'paid') // 請求済み注文のみ |> tap(function ($o) use (&$paidCount, &$bigOrders) { // 高額注文だけ保存 $paidCount++; if ($o['total'] > 1000) { $bigOrders[] = $o; } }) |> map(fn($o) => $o['total']) // 金額を取り出す |> reduce(fn($acc, $yen) => $acc + $yen, 0); // 合計金額を計算 $average = $paidCount ? $sum / $paidCount : 0; printf("請求済み注文数: %d 件\n", $paidCount); printf("平均金額: ¥%d\n", (int)$average); echo "---- 高額注文一覧 ----\n"; foreach ($bigOrders as $o) { printf("注文ID=%d 金額=¥%d\n", $o['id'], $o['total']); }
Output for git.master
請求済み注文数: 3 件 平均金額: ¥1200 ---- 高額注文一覧 ---- 注文ID=101 金額=¥1200 注文ID=103 金額=¥1500

This tab shows result from various feature-branches currently under review by the php developers. Contact me to have additional branches featured.

Active branches

Archived branches

Once feature-branches are merged or declined, they are no longer available. Their functionality (when merged) can be viewed from the main output page


preferences:
152.82 ms | 1007 KiB | 7 Q