3v4l.org

run code in 200+ php & hhvm versions
Bugs & Features
<?php $vouchers = array( 1 => 100, 3 => 150, 5 => 100 ); $discounts = array(); $orders = array(50, 100, 200, 300, 500, 1000); foreach ($orders as $order) { $vouchers2 = $vouchers; foreach ($vouchers2 as $voucher) { $discounts[$order][$voucher] = 0; } $remainingValue = $order; $voucher = array_pop($vouchers2); if ($voucher === null) { continue; } while($remainingValue > 0 && $voucher !== null) { $value = min ($remainingValue, $voucher); $discounts[$order][$voucher] = $value; $voucher = array_pop($vouchers2); } } var_dump($discounts);
based on e60Pv
Output for 4.3.0 - 7.2.0
array(6) { [50]=> array(2) { [100]=> int(50) [150]=> int(50) } [100]=> array(2) { [100]=> int(100) [150]=> int(100) } [200]=> array(2) { [100]=> int(100) [150]=> int(150) } [300]=> array(2) { [100]=> int(100) [150]=> int(150) } [500]=> array(2) { [100]=> int(100) [150]=> int(150) } [1000]=> array(2) { [100]=> int(100) [150]=> int(150) } }