### re: Daily Challenge #4 - Checkbook Balancing VIEW POST

PHP

It wasn't specified, but I sorted the check order. Also noticed that checks 123 and 129 are repeated two and three times, respectively, while 126, 128, and 131 are missing. I'm guessing the duplicate number were supposed to be the missing numbers. 😄

``````\$text = '1233.00
125 Hardware;! 24.8?;
123 Flowers 93.5
127 Meat 120.90
120 Picture 34.00
124 Gasoline 11.00
123 Photos;! 71.4?;
122 Picture 93.5
132 Tires;! 19.00,?;
129 Stamps 13.6
129 Fruits{} 17.6
129 Market;! 128.00?;
121 Gasoline;! 13.6?;';

function checkbook_report(string \$str) {
\$data = format_checkbook_string(\$str);
\$balance = floatval(array_shift(\$data));
\$output = 'Original Balance: ' . number_format(\$balance, 2) . PHP_EOL;
\$expenses = [];

sort(\$data);

foreach (\$data as \$index => \$line) {
\$parts = explode(' ', \$line);
// handles multi-word categories (even though they don't exist in this challenge)
foreach (\$parts as \$line_segment) {
if (\$line_segment != end(\$parts)) {
\$output .= "\$line_segment ";
}
}
\$expenses[] = floatval(end(\$parts));
\$balance -= end(\$expenses);
\$output .= number_format(end(\$parts), 2) . ', Balance: ' . number_format(\$balance, 2) . PHP_EOL;
}

\$total_expenses = array_sum(\$expenses);
\$output .= 'Total expenses: ' . number_format(\$total_expenses, 2) . PHP_EOL;
\$output .= 'Average expense: ' . number_format(\$total_expenses / count(\$expenses), 2) . PHP_EOL;
return \$output;
}

function format_checkbook_string(string \$str) {
\$data = explode(PHP_EOL, \$str);
return array_map('filter_line', \$data);
}

function filter_line(string \$line) {
return preg_replace('/[^\w\s.]+/', '', \$line);
}

echo checkbook_report(\$text);
``````
code of conduct - report abuse  