/    Sign up×
Community /Pin to ProfileBookmark

Sum of Variables

This problem started life as a javascript issue, but I think the solution is more php orientated.

I have created a function that takes its inputs passed from a loop.

[code=php]function despatch($ref, $product, $lngth, $wdth, $wt, $type){
//calculations here
}[/code]

The variables correspond to fields in MySQL recordset row. It calculates the delivery charges finishing with a variable called $fincharge. That bit works well. However, as I am calculating totals on the fly and not saving them in a table, I can not calculate the total delivery cost if there is more than one $fincharge because the function calculates a $fincharge for each item, returns the result, ‘forgets’ the result and then runs the function for the next item in the loop.

I have considered array_push, but I believe it raises a warning if the first input is not already an array.

Does anybody know how to create a sum of variables when each ‘list’ is of an unknown length and each variable effectively has the same name?

More info can be happily supplied.

to post a comment
PHP

4 Comments(s)

Copy linkTweet thisAlerts:
@NogDogJun 30.2011 — One possibility would be to add a $sum parameter to the function, and have it passed by reference. Then as long as you use the same variable name on each call to that function, at any time you can then look at it and see what the current total is.
[code=php]
<?php
// note the "&" in front of &$sum
function despatch($ref, $product, $lngth, $wdth, $wt, $type, &$sum){
//calculations here
$fincharge = 1; // just for testing
$sum += $fincharge;
return $fincharge;
}

for($ix=1; $ix <= 5; $ix++) {
$result = despatch(1, 2, 3, 4, 5, 6, $total);
printf("<p>#%d: This charge: %d, Sub-Total: %d</p>n", $ix, $result, $total);
}
echo "<p>Grand total: $total</p>";
[/code]

Output:
<i>
</i>#1: This charge: 1, Sub-Total: 1

#2: This charge: 1, Sub-Total: 2

#3: This charge: 1, Sub-Total: 3

#4: This charge: 1, Sub-Total: 4

#5: This charge: 1, Sub-Total: 5

Grand total: 5
Copy linkTweet thisAlerts:
@GleddersauthorJul 01.2011 — Nog Dog. (Terry Pratchett fan by any chance?)

Thank you for your reply. I'm working on it now and have a quick question. You have put an ampersand (&) before the $sum variable. Is that a typo or something I have not yet discovered in the language? I'm thinking global variable maybe.

If this sounds like a daft question, I'm a VB convert teaching myself AJAX although I've been using php for about 5 years. There are gaps in my knowledge due to the lack of formal tutoring although I usually get the job done.

Anyway, your answer has certainly given me the inspiration I needed. Thankyou.
Copy linkTweet thisAlerts:
@NogDogJul 01.2011 — Terry Pratchett is my favorite living author. ?

The "&" means that variable is being passed by reference. Otherwise, by default function parameters are copies* and anything done to them within the scope of the function is local only to that scope, whereas the passed-by-reference variable is sort of like a C pointer, so anything the function does to that variable affects it in the global scope, too.

Ultimately, a possible "better" solution would be to define a class that would include that function and also a class variable that would keep track of the total for you, keeping things self-contained within a single object.

______________
  • * As of PHP 5.0, objects are always passed by reference.**

    **
    If you're a Pratchett fan, I figured you'd enjoy some footnotes.
  • Copy linkTweet thisAlerts:
    @GleddersauthorJul 01.2011 — Nog Dog.

    Interesting stuff. C is one language I have never dabbled with and nothing from my VB(and A) experience is similar in concept. In fact the Option Explicit or Private declarations work exactly the opposite way. Of course I could have been asleep during a relevant lecture...

    The solution I came up with was actually to declare a global variable, echo it out in the loop in the page and return it back to the function which then just effectively 'echoes' out the total once it has finished the loop. As this is an AJAX page, it works perfectly, (ie, variable is destroyed on every AJAX request,) so I'll leave it alone. However, I fully understand your reply and wish to thank you for a thoughtful response.

    (I had to stop reading discworld novels because I never got any work done. A major problem when you are not on salary! However you have made me decide that I must re-visit Mr P's great work. Thanks for that too!)
    ×

    Success!

    Help @Gledders spread the word by sharing this article on Twitter...

    Tweet This
    Sign in
    Forgot password?
    Sign in with TwitchSign in with GithubCreate Account
    about: ({
    version: 0.1.9 BETA 5.17,
    whats_new: community page,
    up_next: more Davinci•003 tasks,
    coming_soon: events calendar,
    social: @webDeveloperHQ
    });

    legal: ({
    terms: of use,
    privacy: policy
    });
    changelog: (
    version: 0.1.9,
    notes: added community page

    version: 0.1.8,
    notes: added Davinci•003

    version: 0.1.7,
    notes: upvote answers to bounties

    version: 0.1.6,
    notes: article editor refresh
    )...
    recent_tips: (
    tipper: @AriseFacilitySolutions09,
    tipped: article
    amount: 1000 SATS,

    tipper: @Yussuf4331,
    tipped: article
    amount: 1000 SATS,

    tipper: @darkwebsites540,
    tipped: article
    amount: 10 SATS,
    )...