• 0

# php Looping through values to perform a calculation

Go to solution Solved by spacer,

## Question

game_over

I have developed a web app that logs children attending a club using PHP and have been asked to add a finance module that calculates how much each member owes based on days they are attending... off the top of my head the only way to do it is to create a query that pulls children based on certain criteria and then loop through the fields to decide whether to charge them.

Here is some sample data:

The important part for now is the days they are attending, if a child is attending monday then the cell holds 1 integer, i the child is not attending on a specified day then it holds a zero.

Here is my god awful code that doesn't even work:

\$query_bc_income_week = Booking::ofClub('Breakfast Club')->term()->get(); // query returns children based on Breakfast Club and which term, the important thing to note is that this works and returns rows.
\$days = Config::get('config.dates'); // array

\$amount = 0;
foreach(\$query_bc_income_week as \$child)
{
foreach(\$days as \$day)
{
\$day = strtolower(\$day);
if(\$child->\$day == 1)
{
\$bc_income_week = (\$amount + 0.50);
}
}
echo \$bc_income_week;

So after the query i put the days (mon-fri) into an array and then set the \$amount to 0.

Then i use a foreach to grab each child which can now be accessed via \$child->column (i.e. \$child->monday)

I have a nested foreach that loops through each day and assigned it to the column.

In English: the for each selects the child and then the second loop selects the day, if the \$child->day column holds 1 then add 0.50 to the amount, after it has looped through 5 days(from the array) it will go back to the next child and do the same for the days here, each time incrementing by 0.50 every time it finds a 1.

\$bc_income_week returns: 0.50.50.50.50.50.50.50.50.50.50.50.50.50.50.50.50.50.5

Sorry for my poor explanation, hope it makes sense, surely there must be a better way to achieve this? It is possible my table structure is the real problem but couldn't think of a easier way to access the data.

This is just one calculation that I need to perform, I also need to get the income based on week, term and for both clubs, that is a lot of queries and loops.

Any ideas how I can do this better?

## Recommended Posts

• 0
spacer

In the code you posted, you're never incrementing \$amount. You're adding to it, but you're never assigning the result of the addition to \$amount so it's never updated.

So to fix your code, you should probably initialize \$amount inside the child loop, so that every child starts at 0, then just you just need to add the assignment statement in there.

Also, I'm not sure what the difference is between \$amount and \$bc_income_week. I am making the assumption that \$amount is the individual child cost, and \$bc_income_week is the total cost for all children...

\$bc_income_week = 0;

foreach(\$query_bc_income_week as \$child)
{
\$amount = 0;

foreach(\$days as \$day)
{
\$day = strtolower(\$day);

if (\$child->\$day == 1)
{
\$amount += 0.50;
}
}

\$bc_income_week += \$amount;
echo "Child's cost: " + \$amount;
}

echo "Total cost for all children: " + \$bc_income_week;

I'm extremely rusty with PHP, so I apologize if the syntax is wrong.

As for the data model question, I don't think anyone would be able to answer that without more knowledge of the problem scope. Designing good data models is an entire field of study/focus for some developers/architects, so it's not a trivial problem to solve.

##### Share on other sites
• 0
game_over

In the code you posted, you're never incrementing \$amount. You're adding to it, but you're never assigning the result of the addition to \$amount so it's never updated.

So to fix your code, you should probably initialize \$amount inside the child loop, so that every child starts at 0, then just you just need to add the assignment statement in there.

Also, I'm not sure what the difference is between \$amount and \$bc_income_week. I am making the assumption that \$amount is the individual child cost, and \$bc_income_week is the total cost for all children...

\$bc_income_week = 0;

foreach(\$query_bc_income_week as \$child)
{
\$amount = 0;

foreach(\$days as \$day)
{
\$day = strtolower(\$day);

if (\$child->\$day == 1)
{
\$amount += 0.50;
}
}

\$bc_income_week += \$amount;
echo "Child's cost: " + \$amount;
}

echo "Total cost for all children: " + \$bc_income_week;

I'm extremely rusty with PHP, so I apologize if the syntax is wrong.

As for the data model question, I don't think anyone would be able to answer that without more knowledge of the problem scope. Designing good data models is an entire field of study/focus for some developers/architects, so it's not a trivial problem to solve.

This works perfect thanks, I know it's not the best way to do it but I can throw it in a function to avoid repeating it.

thank you

##### Share on other sites
• 0
spacer

Glad I could help! Good luck with the rest of your project.

##### Share on other sites
This topic is now closed to further replies.

• ### Similar Content

• By News Staff
Get the Complete 2021 Superstar Backend Developer Bundle for only \$39.99
by Steven Parker

Today's highlighted deal comes via our Online Courses section of the Neowin Deals store, where you can save 98% off the Complete 2021 Superstar Backend Developer Bundle. Explore the server-side of web and app development with 35+ hours of content on HTML5, CSS3, Ruby, Python, PHP, and more.

This bundle consists of the following courses:

HTML5 CSS3 JQUERY Single-Page Website Project from Scratch
Build Your Own Website from Scratch Using HTML5 CCS JQUERY Java Basics: Learn To Code The Right Way
Take on the Java Basics & Fast Track Your Way to Building Desktop + Android Apps Introduction to Ruby Programming
Explore the Ruby Programming Language from the Ground Up Ruby on Rails for Web Development
Learn Ruby on Rails the Fast & Easy Way! Master the Fundamentals of Python
Gain Solid Python Understanding & Create Your Own Programs Python Programming For Everyone
Learn Python Programming, from the Very Basic to Advanced Concepts, & How to Start Writing and Running Python Code JSON AJAX Data Transfer to MySQL Database Using PHP
Create a Dynamic Input Form That Can Add Data & Retrieve Data from a MySQL Database PHP Development & Predefined Variables
Have a Stronger Understanding of the PHP Programming Language & Create More Interactive Websites AJAX Connection to MySQL PHP API
Create a Simple Database API Which Can Be Accessed from Frontend Code, Updated & More PHP Programming For Everyone
Learn PHP Programming for Web Development the Fast & Easy Way! Functional Programming in JavaScript
Begin Applying Functional Programming Techniques Into Their Own Code JavaScript Programming For Everyone
Learn to Code JavaScript Like a Professional Programmer Beginner Object Oriented Programming in C# and .NET Core
Learn Object-Oriented Programming Fundamentals & Climb Up the Developer Hierarchy Good to know
Length of time users can access this course: lifetime Certificate of completion included Redemption deadline: redeem your code within 30 days of purchase Updates included For a full description, specs, and instructor info, click here.

Here's the deal:
This Complete 2021 Superstar Backend Developer Bundle normally costs \$2,587, but you can pick it up for just \$39.99 for a limited time - that represents a saving of \$2,547.01 (98%) off.

Spring Sale Promo
Until tomorrow April 13, for every \$75 spent, get \$10 in store credit.

See all discounted Online Courses. This is a time-limited offer.
Get \$1 credit for every \$25 spent · Give \$10, Get \$10 · 10% off for first-time buyers.

Not for you?
That's OK, there are other deals on offer you can check out here.

Enter giveaways: Polycade Home Arcade | \$5K in cash | \$10K in Crypto Ivacy VPN - 5 year subscription for just \$1 per month NordVPN - 2 year subscription at up to 68% off Private Internet Access VPN - subscriptions at up to 71% off Unlocator VPN or SmartDNS - unblock Geoblock with 7-day free trial Neowin Store for our preferred partners. Subscribe to Neowin - for \$14 a year, or \$28 a year for Ad-Free experience Disable Sponsored posts · Neowin Deals · Free eBooks · Neowin Store

Disclosure: This is a StackCommerce deal or giveaway in partnership with Neowin; an account at StackCommerce is required to participate in any deals or giveaways. For a full description of StackCommerce's privacy guidelines, go here. Neowin benefits from shared revenue of each sale made through our branded deals site, and it all goes toward the running costs.

• By News Staff
Pay What You Want for this Full Stack Web Development Bundle
by Steven Parker

Today's highlighted deal comes via our Online Courses section of the Neowin Deals store, where you can Pay What You Want for this Full Stack Web Development Bundle. The world's best developers are Full Stack developers. Here's 122+ hours of instruction to help you join them.

How does it work?
With the Pay What You Want bundles, you can get something incredible for as little as you want to pay. And if you beat the average price, you’ll receive the fully upgraded bundle! Included in this Pay What You Want deal, are the following courses:

Pay What You Want (as little as \$1) for the unlocked item:

Projects in HTML5
Build 10 Products in HTML5 & JavaScript Or bid the average price to also get the following items:

The Full Stack Web Development Course
Handle Every Facet of An App's Development, Ascend to the Top of the Developer Mountain Projects In ReactJS: The Complete React Learning Course
Dive Into One of Today's Most In-Demand Front End Development Tools Projects in JavaScript & JQuery
Gain Practical Experience in JavaScript & jQuery By Completing 10 Projects ReactJS and Flux: Learn By Building 10 Projects
Learning These Facebook-Created Development Tools Will Greatly Accelerate Your Workflow Projects in MongoDB: Learn MongoDB Building 10 Projects
Explore the World's Most Popular Cross-Platform NoSQL Database Projects Using PHP Frameworks
Build 10 Unique Projects to Get a Complete Grasp On Multiple PHP Frameworks Learn NodeJS by Building 10 Projects
Use This Popular Runtime Environment to Craft Lightweight, Highly Scalable Apps Here's the deal:
The bundle represents an overall retail value of \$476 But you can Pay What You Want for the unlocked items (as little as \$1) Beat the average price and you'll take home the entire bundle. Beat the Leader's price and get entered into the epic giveaway. Pay What You Want for this Full Stack Web Development Bundle
See other Pay What You Want deals. This is a time-limited deal that ends soon.
Get \$1 credit for every \$25 spent · Give \$10, Get \$10 · 10% off for first-time buyers.

Not for you?
That's OK, there are other free eBooks on offer you can check out here.

Home Gym Giveaway | Bitcoin (BTC) Investment Giveaway Ivacy VPN - 5 year subscription for just \$1 per month NordVPN - 2 year subscription at up to 68% off Private Internet Access VPN - subscriptions at up to 71% off Unlocator VPN or SmartDNS - unblock Geoblock with 7-day free trial Neowin Store for our preferred partners. Subscribe to Neowin - for \$14 a year, or \$28 a year for Ad-Free experience Disable Sponsored posts · Neowin Deals · Free eBooks · Neowin Store

• By News Staff
Save 97% off this Complete Front-End Developer Bundle
by Steven Parker

Today's highlighted deal comes via our Online Courses section of the Neowin Deals store, where for only a limited time you can save 97% off this Complete Front-End Developer Bundle. Start building websites from scratch with 66 hours of training in JavaScript, CSS, Adobe Design Tools and more.

What's the deal?
This deal consists of the following courses:

Learn CSS Web Design & Development
Learn How to Apply CSS Styling to HTML Elements Complete Bootstrap 4 Course: Build 5 Projects From Scratch
Get Familiar with Bootstrap 4, One of the Best Tools for Rapid Site Design & Development Adobe Illustrator CC 2018 Master Class
Master the Industry-Standard Vector Graphics Application Step-by-Step HTML & CSS for Absolute Beginners
Create Your Own Web Pages with HTML & CSS JavaScript for Beginners
Learn JavaScript Through Whiteboard Videos, Coding In the Browser & Building a Website JavaScript Specialist Designation
Study to Pass the JavaScript Specialist Designation Exam React for Absolute Beginners
The Complete Guide to Professional Development Using React Mastering Mobile App Design With Sketch 3
The Beginner's Guide to Awesome Mobile App Development Adobe Photoshop CC: Your Complete Beginner's Guide
The World's Most Popular Photo Editing Software Taught to You From A to Z Good to know
Length of time users can access courses: lifetime Certification of completion included Redemption deadline: redeem your code within 30 days of purchase For full details, terms, and instructor info for the above courses, click here.

Here's the deal:
This Complete Front-End Developer Bundle normally costs \$1,419.97, but you can pick this up for just \$41 for a limited time, that's a saving of 97% (\$1,378.97) off the normal price!

See all discounted Online Courses on offer. This is a time-limited deal.
Get \$1 credit for every \$25 spent · Give \$10, Get \$10 · 10% off for first-time buyers.

Not for you?
That's OK, there are other deals on offer you can check out here.

Home Gym Giveaway | Ultimate Gaming Giveaway (feat. PlayStation 5 & Xbox Series X) Ivacy VPN - 5 year subscription for just \$1 per month NordVPN - 2 year subscription at up to 68% off Private Internet Access VPN - subscriptions at up to 71% off Unlocator VPN or SmartDNS - unblock Geoblock with 7-day free trial Neowin Store for our preferred partners. Subscribe to Neowin - for \$14 a year, or \$28 a year for Ad-Free experience Disable Sponsored posts · Neowin Deals · Free eBooks · Neowin Store

Disclosure: This is a StackCommerce deal or giveaway in partnership with Neowin; an account at StackCommerce is required to participate in any deals or giveaways. For a full description of StackCommerce's privacy guidelines, go here. Neowin benefits from shared revenue of each sale made through our branded deals site, and it all goes toward the running costs.

• By News Staff
Save 94% off the cost of this Essential PHP Coding Bundle
by Steven Parker

Today's highlighted deal comes via our Online Courses section of the Neowin Deals store, where for only a limited time, you can save 94% off this Essential PHP Coding Bundle. Get started in web development by learning the fundamentals of PHP coding and practicing object-oriented programming.

This bundle consists of the following courses:

Fundamentals of PHP Training Course
Learn the Basic Programming Concepts in the Most Popularly Used Server-Side Programming Language PHP Development with the Laravel Framework Training Course
Develop Homepages, Create Accounts & Activate Emails Using the Open-Source Laravel PHP Framework PHP Object Oriented Programming: Build a Login System Training Course
Create an R/L System Using PHP & OOP Together Python Object Oriented Programming Fundamentals Training Course
Create Advanced & Easily Maintainable Python Applications with Object-Oriented Programming Good to know
Length of time users can access this course: 1 Year Certification of completion included Redemption deadline: redeem your code within 30 days of purchase For specifications and instructor info please click here.

Here's the deal:
This Essential PHP Coding Bundle normally costs* \$516, but it can be yours for just \$29.99 for a limited time, that's a saving of \$486.01 (94%).

See all Online Courses on offer. This is a time-limited offer that ends soon.
Get \$1 credit for every \$25 spent · Give \$10, Get \$10 · 10% off for first-time buyers.

Not for you?
If this offer doesn't interest you, why not check out the following offers:

The Win Your Dream 2020 Tesla Model 3 Giveaway
20% off Ivacy VPN subscription with coupon code IVACY20 NordVPN subscription at up to 68% off for a 2 year plan Private Internet Access VPN subscription at up to 71% off Unlocator VPN or SmartDNS unblock Geoblock with 7-day free trial Disable Sponsored posts · Other recent deals · Preferred partner software

Disclosure: This is a StackCommerce deal or giveaway in partnership with Neowin; an account at StackCommerce is required to participate in any deals or giveaways. For a full description of StackCommerce's privacy guidelines, go here. Neowin benefits from shared revenue of each sale made through our branded deals site, and it all goes toward the running costs.

• By News Staff
Get this Interactive Learn to Code Bundle at 73% off for just \$29.99
by Steven Parker

Today's highlighted deal comes via our Online Courses section of the Neowin Deals store, where you can save 73% off the Interactive Learn to Code Bundle. Start writing codes and programs from scratch with 9 interactive courses on SQL, JavaScript, PHP, jQuery, BootStrap, and more.

This deal consists of the following courses:

An Interactive SQL Tutorial for Beginners: Introduction to SQL
Getting Started with SQL Doesn't Have to Be Hard An Interactive JavaScript Course for Beginners
Learn JavaScript Interactively with a One-of-a-Kind JS Online Course Interactive jQuery Tutorial: Learn jQuery Step-by-Step
Take an Interactive jQuery Training Course for Beginners to Quickly Master jQuery Events, Effects & More Learn PHP Online: PHP Basics Explained in an Interactive & Fun Manner
An Interactive Tutorial for Beginners Who Want to Master PHP Basics in a Non-Boring Way The Complete Solidity Smart Contract Guide
Master Solidity Programming Through Hands-On Experience Master Python Fundamentals the Fun Way: An Interactive Python Tutorial
A Python Training Course for Absolute Beginners Who Wants to Master the Language Without Getting Bored A Responsive Web Design Course: Find Out How to Create a Responsive Website
Make a Website Mobile-Friendly with a Step by Step, Responsive Web Design Tutorial Bootstrap Tutorial: Learn to Create Dynamic Websites in a Pinch
Find Out How to Use Bootstrap the Fun Way by Using an Interactive Course An Interactive Java Tutorial: Learn by Practice!
Learn Java From Scratch by Combining Theory with Hands-On Coding Experience Good to know
Length of time users can access this course: lifetime Certification of completion included Redemption deadline: redeem your code within 30 days of purchase For a full description, specs, and instructor info, click here.

Here's the deal:
This Interactive Learn to Code Bundle normally costs* \$112, but you can pick it up for just \$29.99 for a limited time - that represents a saving of \$82.01 (73%) off.

See all discounted Online Courses. This is a time-limited offer.

Get \$1 credit for every \$25 spent · Give \$10, Get \$10 · 10% off for first-time buyers.

Not for you?
If this offer doesn't interest you, why not check out the following offers:

The Win Your Dream 2020 Tesla Model 3 Giveaway
The Nintendo Gaming Bundle Giveaway 20% off Ivacy VPN subscription with coupon code IVACY20 NordVPN subscription at up to 68% off for a 2 year plan Private Internet Access VPN subscription at up to 71% off Unlocator VPN or SmartDNS unblock Geoblock with 7-day free trial Disable Sponsored posts · Other recent deals · Preferred partner software

Disclosure: This is a StackCommerce deal or giveaway in partnership with Neowin; an account at StackCommerce is required to participate in any deals or giveaways. For a full description of StackCommerce's privacy guidelines, go here. Neowin benefits from shared revenue of each sale made through our branded deals site, and it all goes toward the running costs.

running costs.