Page 1 of 1

PHP Random Float Help

Posted: Sun May 21, 2017 6:16 pm
by Fireal
PHP beginner here and I am trying to use the code below to generate 5 random floats and then add them together. However, keep running in to a "Cannot Redeclare" error. Any help or suggestions? Thanks!

Code: Select all

function RandRoll($mod1, $mod2){

$modCalc = 1.00 + $mod1 + $mod2;
echo "(" . $modCalc . ")"; 

$RAND_MIN = $modCalc;
$RAND_MAX = 100.00;


function frand($min, $max, $decimals = 0) {
  $scale = pow(10, $decimals);
  return mt_rand($min * $scale, $max * $scale) / $scale;
}

$result = frand($RAND_MIN, $RAND_MAX, 2);

    return $result;

}

$moda1 = 23.45;
$moda2 = 17.21;
$score1 = RandRoll($moda1, $moda2);
$score2 = RandRoll($moda1, $moda2);
$score3 = RandRoll($moda1, $moda2);
$score4 = RandRoll($moda1, $moda2);
$score5 = RandRoll($moda1, $moda2);

echo $score1 + $score2 + $score3 + $score4 + $score5;

Re: PHP Random Float Help

Posted: Mon May 22, 2017 3:05 am
by Jackolantern
I don't see any problem in the code. Are you including this file into other files? If so, it may be getting included multiple times which will cause an error because your function is being declared multiple times. You can test to see if that is the case by wrapping your function in this:

Code: Select all

if (!function_exists('RandRoll')) {
    function RandRoll($mod1, $mod2) {
       // ...
    }
}
However, I would not leave it that way even if that ends up fixing it. Instead you should track down why it is being executed multiple times.

Re: PHP Random Float Help

Posted: Mon May 22, 2017 11:48 pm
by KyleMassacre
What I would suggest trying out is seeing if you can break up your functions instead of a function nested inside another function. Instead of:

Code: Select all

function myFuncOne() {
  ....
    function myFuncTwo() {
        ....
    }
}
 
Do:

Code: Select all

function myFuncOne() {
    ....
}

function myFuncTwo() {
    ....
}
 
Plus it's a little cleaner to look at