Forum Moderators: coopster

Message Too Old, No Replies

Adding values in loop

         

Patrick Taylor

1:45 pm on Jul 1, 2006 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



I'd welcome some assistance with adding values from a loop to arrive at a total. I've put this together:


// Fetch and print all the records
while ($row = mysql_fetch_array($result, MYSQL_NUM)) {
// Convert $row[0] string to array with " : " separator
$myArray = explode(" : ", $row[0]);
// Extract second element of array
$slice = array_slice($myArray, 1, 1);
foreach ($slice as $val) {
echo $val;
}
}

The $row[0] is a string with values separated by space-colon-space. I've converted it to an array and extracted the second element - the one I want - and been able to print a list of the values. They are numbers, and what I really want to do is not to print the list but to arrive at a total of them all added together. I just want to print the value of the $vals all totalled up (if that makes sense).

I've got confused with all my loops, and would welcome some help.

coopster

2:03 pm on Jul 1, 2006 (gmt 0)

WebmasterWorld Administrator 10+ Year Member



First, why not store the values in their own columns in the database as opposed to "space-colon-space" entries in a single column? Sure would make your processing much easier ;)

To do what you desire, simply initialize a numeric variable to store your total and add to it each time:

$total = 0; // initialize 
// Fetch and print all the records
while ($row = mysql_fetch_array($result, MYSQL_NUM)) {
// Convert $row[0] string to array with " : " separator
$myArray = explode(" : ", $row[0]);
// Extract second element of array
$slice = array_slice($myArray, 1, 1);
$total += $slice[0];
}

Patrick Taylor

2:40 pm on Jul 1, 2006 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



coopster, thanks for that, as always.

The reason for "space-colon-space" is because the string comes from a shopping cart, with a set of values separated in that way, I suppose so that they can be converted into an array if required.

Thanks again,

Patrick

<added>I'm just curious why it's $slice[0] - is $slice still an array?</added>

coopster

4:37 pm on Jul 1, 2006 (gmt 0)

WebmasterWorld Administrator 10+ Year Member



>>shopping cart

Gotcha. I suppose in case you weren't using a database but a text file instead.

Yes, the return type from the array_slice() [php.net] function is indeed an array:

array array_slice ( array array, int offset [, int length [, bool preserve_keys]] )

You see that very first word, array? There is a page in the PHP manual that describes How to read a function definition [php.net] that will be of great help.