Incrementing a random integer using sessions

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
Imtiyaaz
Forum Newbie
Posts: 8
Joined: Thu Feb 02, 2012 5:52 am

Incrementing a random integer using sessions

Post 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 :)
User avatar
Celauran
Moderator
Posts: 6427
Joined: Tue Nov 09, 2010 2:39 pm
Location: Montreal, Canada

Re: Incrementing a random integer using sessions

Post 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;

?>
Imtiyaaz
Forum Newbie
Posts: 8
Joined: Thu Feb 02, 2012 5:52 am

Re: Incrementing a random integer using sessions

Post by Imtiyaaz »

Great, it works. Thanks

and thank you for the explanation as well :D
User avatar
Celauran
Moderator
Posts: 6427
Joined: Tue Nov 09, 2010 2:39 pm
Location: Montreal, Canada

Re: Incrementing a random integer using sessions

Post 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'];
Post Reply