0

How to summ values of 'age' in multid. array(php): $staff=array(array('name'='Ber', 'age'='30'), array('name'=Ol', 'age'='25')

How to sum values of index 'age' in multidimensional array PHP: $staff=array(array('name'=》'Berik', 'age'=》'30'), array('name'=》'Oleg', 'age'=》'25'). need to summ 'age' and then to find average number

25th Jun 2018, 2:06 PM
Berik Janberbayev
Berik Janberbayev - avatar
3 Answers
+ 4
You need to have the age as integer rather than string, so do as follows: 'age' => 30 Instead of: 'age' => '30' <?php $staff=array(array('name'=>'Berik', 'age'=>30), array('name'=>'Oleg', 'age'=>25)); $sum = 0; $items = 0; foreach($staff as $emp) { $sum += $emp['age']; $items++; } $avg = $sum / $items; echo "There are $items employees, with an average of age $avg years"; ?> Hth, cmiiw
27th Jun 2018, 12:14 AM
Ipang
+ 2
You're welcome, glad to help : )
30th Jun 2018, 5:21 PM
Ipang
+ 1
thanks a lot. I was thinking so many days. Highly appreciated.
30th Jun 2018, 5:10 PM
Berik Janberbayev
Berik Janberbayev - avatar