[Solved] Incrementing and resetting a PHP session variable


You write PHP in the middle of some JavaScript functions as if you expect it to be executed by the JavaScript itself.

If you remove the HTML/JS output, you can see what actually happens on the server as soon as you load the page (I assume your code snippets are in order):

session_start();
if (!isset($_SESSION['score'])) 
    $_SESSION['score'] = 0;

if (!isset($_SESSION['skipped'])) 
    $_SESSION['skipped'] = FALSE;

if($_SESSION['skipped'] == TRUE){
    $_SESSION['score'] = 0;
    $_SESSION['skipped'] = !$_SESSION['skipped'];
}
$x = $_SESSION['score'] + 1;
$_SESSION['score'] = $x;

$q = TRUE;
$_SESSION['skipped'] = $q;

On the first page load with an empty session, this will set $_SESSION['score'] to 0 (because it’s not set yet), then increment it to 1, then set $_SESSION['skipped'] to true.

On subsequent page loads, it will set $_SESSION['score'] to 0 (because skipped is set), then increment it again to 1 and finally setting skipped to true again (you see: nothing changed)

1

solved Incrementing and resetting a PHP session variable