Forum Moderators: coopster

Message Too Old, No Replies

$variable + $variable = error

         

ronnyskog

12:24 pm on Jun 17, 2010 (gmt 0)

10+ Year Member



Im puzzled by the result of adding two wariables together in my script. The script loops throug an array and is supposed to calculate running a total of hours worked:



$counter = 1;

while ( $counter <= 100 ) {
$counter = $counter + 1;

echo $array[$counter][1]; //name
echo $array[$counter][2]; //hours worked

echo "- <br>";

$arrhr = $array[$counter][2]; //number of hours worked
echo $arrhr;

$hr = $hr + $arrhr;
echo "$hr + $arrhr =" . $hr;

}


The scripts seems to loop through the array and output the values (names and hours worked) correctly. But the last echo statement comes out like this:

0 +
4.5
=0


If i change the code to
$hr = $arrhr + $arrhr;
echo "$arrhr + $arrhr =" . $hr;

The output is

4.5
+
4.5
=0


The $arrhr value is correct, but "+" does not seem to do anything.

Im sure Im missing something obvious :)

penders

1:25 pm on Jun 17, 2010 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



What is the output from the penultimate echo?

The value of $counter in your loop is going from 2 to 101. Is that correct? It kinda looks like you could be out by 1 or may be even 2? Numeric array indices generally start from 0. You could be going past the end of your array?

You should also initialise your $hr var at the start of your script to 0 (on the first iteration of your loop... $hr = $hr + $arrhr ... $hr = what? + $arrhr) - although that does not appear to be the cause of your current problem.

If you have full error_reporting() enabled at the start of your script, then PHP should alert you to these sort of potential problems. ie
error_reporting(E_ALL | E_STRICT); 
ini_set('display_errors','On');

ronnyskog

3:24 pm on Jun 17, 2010 (gmt 0)

10+ Year Member



Thank you for your suggestions.

I finally figured it out. The problem was that that the array actually contained hidden html and was a treated like a string.

This code works:



$arrhr = $array[$counter][2];

//Remove html <p> and </p>
$arrhr = str_replace('<p>', '', $arrhr);
$arrhr = str_replace('</p>', '', $arrhr);

//change value type from string to float
settype($arrhr, "float");

echo "$hr + $arrhr = ";
$hr = $hr + $arrhr;
echo $hr;

ronnyskog

3:28 pm on Jun 17, 2010 (gmt 0)

10+ Year Member



Even better:

$arrhr = $array[$counter][2];

//Remove html
$arrhr = strip_tags($arrhr);

echo "$hr + $arrhr = ";
$hr = $hr + $arrhr;
echo $hr;


}

Readie

6:12 pm on Jun 17, 2010 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



settype($arrhr, "float");

I know you're not using this anymore, but the above could be achieved like this:

$arrhr = (float) $array[$counter][2];

[php.net...]