Page 1 of 1

incrementation

Posted: Thu Oct 14, 2010 1:12 pm
by mapixu
Here is the the code that's making me go a little mangos, not bananas. If someone could...

Code: Select all

<?php
// initialize a session
session_start();
if(isset($_SESSION['counter'])){ 
   //echo "<em><b>You have viewed this page</b></em> " . $_SESSION['counter']++ . " <em><b>times</b></em>";
   echo "<em><b>You have viewed this page</b></em> ". $_SESSION['counter']+=1  ." <em><b>times</b></em>";
}else{ 
   echo "<em><b>You have only viewed this page</b></em> " . $_SESSION['counter']=1 . "&nbsp;<em><b>times</b></em>";
}  
?>
Ok! question: Why is it that when I echo $_SESSION['counter']+=1, idon't get to see the following line: <em><b>times</b></em>"; , on my browser but , echo "<em><b>You have viewed this page</b></em> " . $_SESSION['counter']++ . " <em><b>times</b></em>"; works just fine.

Thanks

Re: incrementation

Posted: Thu Oct 14, 2010 1:56 pm
by Gargoyle
use

Code: Select all

($_SESSION['counter']+=1)

Re: incrementation

Posted: Thu Oct 14, 2010 5:36 pm
by requinix
It's operator precedence. You know how, in math, multiplication and division are more "important" then addition and subtraction? 1 + 2 * 3 = 1 + (2 * 3) and not (1 + 2) * 3.

Same in PHP. Normal addition (+) and string concatenation (.) have a higher precendece than normal assignment (=) and additive assignment (+=). So

Code: Select all

$variable += 1 . "string";
is equivalent to

Code: Select all

$variable += (1 . "string")
To change how it works you need parentheses.