3v4l.org

run code in 300+ PHP versions simultaneously
<?php $array = array( 'code 10 and amount 1000', 'code 10 and amount 200', 'code 10 and amount 300', 'code 20 and amount 2000' ); $output = array(); foreach ($array as $value) { // Extract the values from the string preg_match('/^code\s(.*)\s\sand amount\s(.*)$/', $value, $match); // If no code exists, we have a problem so skip the line if (! isset($match[1])) { continue; } // Make this a bit more readable for future devs $code = (int) $match[1]; $amount = (int) isset($match[2]) ? $match[2] : 0; // If the code exists in the output array, add the value to it if (isset($output[$code])) { $output[$code] += $amount; } else { // Else make the new code have the value $output[$code] = $amount; } } print_r($output); exit;
Output for 4.3.0 - 4.3.11, 4.4.0 - 4.4.9, 5.0.0 - 5.0.5, 5.1.0 - 5.1.6, 5.2.0 - 5.2.17, 5.3.0 - 5.3.29, 5.4.0 - 5.4.45, 5.5.24 - 5.5.35, 5.6.7 - 5.6.28, 7.0.0 - 7.0.20, 7.1.0 - 7.1.25, 7.2.0 - 7.2.33, 7.3.0 - 7.3.33, 7.4.0 - 7.4.33, 8.0.0 - 8.0.30, 8.1.0 - 8.1.28, 8.2.0 - 8.2.18, 8.3.0 - 8.3.6
Array ( [10] => 1500 [20] => 2000 )

preferences:
197.52 ms | 406 KiB | 329 Q