Skip to content

Instantly share code, notes, and snippets.

@anvyst
Created January 22, 2013 06:26
Show Gist options
  • Save anvyst/4592560 to your computer and use it in GitHub Desktop.
Save anvyst/4592560 to your computer and use it in GitHub Desktop.
<?php
/* Closures & Anonymous functions test */
$data = array(
array(
'name' => 'John',
'quantity' => '15',
'price' => '5.00'
),
array(
'name' => 'Wess',
'quantity' => '10',
'price' => '2.50'
)
);
function calc_totals(array $cart, $vat) {
$new_data = array_map(
function( array $position ) use ($vat) {
$sum = $position['price'] * $position['quantity'];
$position['gross'] = $sum;
$position['tax'] = $sum / ( 100 + $vat ) * $vat;
$position['net'] = $sum - $position['tax'];
return $position;
},
$cart
);
print_r($new_data);
return array_reduce( $new_data,
function( $totals, $position ) {
$totals['gross'] += $position['gross'];
$totals['net'] += $position['net'];
$totals['tax'] += $position['tax'];
return $totals;
},
array( 'gross' => 0, 'tax' => 0, 'net' => 0)
);
}
$result = calc_totals( $data, 19 );
print_r($result);
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment