Page 1 of 1

Incrementing a random integer using sessions

Posted: Thu Feb 02, 2012 6:29 am
by Imtiyaaz
Hi

Im using the rand() function to generate a random integer. Every time the page refreshes I want the new random number to be added to the previously generated random number, thus creating a running total of randomly generated numbers...this is what I have so far but its not working, instead of creating a running total its just doubling up the random integer...any assistance will be much appreciated

Code: Select all

<?php
error_reporting(0); // turn error messages off
$random = rand();
$newRandom = $random;
echo "The random number is ".$random;
echo "<br>";
echo "<br>";


session_start(); // start a session
$_SESSION['newRandom'] = $newRandom;

if(isset($_SESSION['newRandom'])){ // check if the random number is stored in the session
		echo "The total so far is " .$_SESSION['newRandom'] += $random;
	}

?>
Thanks :)

Re: Incrementing a random integer using sessions

Posted: Thu Feb 02, 2012 6:34 am
by Celauran
You're assigning $newRandom to the $_SESSION variable before checking if it previously existed, thus overwriting it. Only then do you check if it exists, which it always will since you just set it.

Code: Select all

<?php

session_start(); // start a session

$random = rand();
$newRandom = $random;

echo "The random number is ".$random;
echo "<br>";
echo "<br>";

// check if the random number is stored in the session
if(isset($_SESSION['newRandom']))
{
    $_SESSION['newRandom'] += $newRandom;
}
else
{
    $_SESSION['newRandom'] = $newRandom;
}

echo "The total so far is " .$_SESSION['newRandom'] += $random;

?>

Re: Incrementing a random integer using sessions

Posted: Thu Feb 02, 2012 7:40 am
by Imtiyaaz
Great, it works. Thanks

and thank you for the explanation as well :D

Re: Incrementing a random integer using sessions

Posted: Thu Feb 02, 2012 8:20 am
by Celauran
Actually, there's still a little mistake. This line

Code: Select all

echo "The total so far is " .$_SESSION['newRandom'] += $random;
should not increment $_SESSION value since we already handled that above.

Corrected:

Code: Select all

echo "The total so far is " .$_SESSION['newRandom'];