Forum Moderators: coopster
// 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.
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];
}
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>
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.