| |||||||||||
| |||||||||||
PHP adding arrays / summing arrays
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);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++) {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++) {Which is slightly longer for my 5 rooms, but much MUCH shorter once we expand! (See full source code here and run it here) (written 2007-03-23 23:17:10) Associated topics are indexed under H106 - PHP - Arrays
Some other Articles
1200 miles in 3 daysThe Last Word on the road Origin of Jack and Jill and little Jack Horner Newport Male Voice Choir PHP adding arrays / summing arrays Unexpected visitors to our site PHP Image upload script File and URL reading in PHP Bank Holiday country breaks in Melksham, Wiltshire Training in Lua 1637 posts, page by page
Link to page ... 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33 at 50 posts per pageThis is a page archived from The Horse's Mouth at http://www.wellho.net/horse/ - the diary and writings of Graham Ellis. Every attempt was made to provide current information at the time the page was written, but things do move forward in our business - new software releases, price changes, new techniques. Please check back via our main site for current courses, prices, versions, etc - any mention of a price in "The Horse's Mouth" cannot be taken as an offer to supply at that price. Link to Ezine home page (for reading). Link to Blogging home page (to add comments). |
| ||||||||||
PH: 01144 1225 708225 • FAX: 01144 1225 707126 • EMAIL: info@wellho.net • WEB: http://www.wellho.net • SKYPE: wellho | |||||||||||