- preg_match: documentation ( source)
- print_r: documentation ( source)
<?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);