Jump to content

[SOLVED] array_sum() help


sandrob57

Recommended Posts

This is my array

 

$income = array( 
			'tax' => array(		'name' => 'Citizen Taxes',
								'amount' => '45',
								'description' => 'in taxes from your citizens.'		
					),
			'house' => array(	'name' => 'Housing Upkeep',
								'amount' => '12',
								'description' => 'in housing upkeep costs.'		
					)
			);

 

I need to get the total of amount. Currently I do:

 

$total = 0;
foreach ($income as $type => $array) {
$total = $total + $income[$type]['amount'];
}

 

I feel this is sloppy, and I would like to figure out how to correctly use the array_sum() function.

 

Edit: I should mention none of the tutorials I could find helped me in multi-dimension arrays.

Link to comment
https://forums.phpfreaks.com/topic/61658-solved-array_sum-help/
Share on other sites

<?php
$income = array( 
'tax' => array(		'name' => 'Citizen Taxes',
			'amount' => '45',
			'description' => 'in taxes from your citizens.'		
),
'house' => array(	'name' => 'Housing Upkeep',
		'amount' => '12',
		'description' => 'in housing upkeep costs.'		
)
);
$amount = 0;
foreach($income as $k_type => $a_value){
       $amount = $amount + $income[$k_type]['amount'];
}
echo $amount;
?>

Link to comment
https://forums.phpfreaks.com/topic/61658-solved-array_sum-help/#findComment-306935
Share on other sites

this should do the same without foreach in foreach 

<?php
$income = array( 
			'tax' => array(		'name' => 'Citizen Taxes',
								'amount' => '45',
								'description' => 'in taxes from your citizens.'		
					),
			'house' => array(	'name' => 'Housing Upkeep',
								'amount' => '12',
								'description' => 'in housing upkeep costs.'		
					)
			);
foreach($income as $value){
$sum .= array_sum($value['amount']);
}
?>

Link to comment
https://forums.phpfreaks.com/topic/61658-solved-array_sum-help/#findComment-306944
Share on other sites

Gah! The operator .= is for string concatentation! Therefore, if you were to have "$x=0; $x.=12; $x.=45; $x.=3894;", $x would then equal "012453894".

Use operator += and define your numbers as numbers, not string literals (enclosed in quotes '').

$sum=0;
foreach ($income as $e) {
$sum+=$e['amount'];
}

I'm not sure why you all are using array_sum() for this either... $income[] is a one-level array. You're not looking for the sum of a multi-dimensional array, you're looking for the sum of specific indexes in sub-arrays.

Link to comment
https://forums.phpfreaks.com/topic/61658-solved-array_sum-help/#findComment-306946
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.