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!
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
<?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;
}
?>
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.
<?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;
?>