Main Content

PHP adding arrays / summing arrays

Archive - Originally posted on "The Horse's Mouth" - 2007-03-23 23:17:10 - Graham Ellis

A question from my mailbox, answered in relation to our hotel. "I have a number of arrays in PHP and I want to add the elements of the arrays together". "There doesn't appear to be an array_sum function".

So in other words, my correspondent may have room occupancy data such as:

$bed1 = array(2,2,2,0,2,0,0);
$bed2 = array(1,1,1,1,1,0,0);
$bed3 = array(1,1,1,0,0,2,2);
$bed4 = array(0,0,0,0,0,0,0);
$bed5 = array(1,1,1,1,1,2,2);


and want to produce a report showing the nightly occupancy - perhaps to know how many breakfasts to prepare. What about

for ($k=0; $k<7; $k++) {
$occupancy[$k] = $bed1[$k]+$bed2[$k]+$bed3[$k]
+$bed4[$k]+$bed5[$k];
}


That code is horrid - it works with our 5 room place, but when we grow to 50 rooms ....

A good solution is to keep the data in an array of arrays - the "1", "2", "3" and so on in the variable names really should itself be a variable / subscript so that the summing can be done with a loop of loops:

$full = array($bed1,$bed2,$bed3,$bed4,$bed5);

combines the bedrooms and the the code to sum looks like:

for ($k=0; $k<7; $k++) {
$sm = 0;
for ($j=0; $j<count($full); $j++) {
$sm += $full[$j][$k];
}
$ot[$k] = $sm;
}


Which is slightly longer for my 5 rooms, but much MUCH shorter once we expand!

(See full source code here and run it here)