PHP Random Float Help

Place for questions and answers for all newcomers and new coders. This is a free for all forum, no question is too stupid and to noob.
Post Reply
Fireal
Posts: 11
Joined: Sun May 21, 2017 5:51 pm

PHP Random Float Help

Post 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;
User avatar
Jackolantern
Posts: 10893
Joined: Wed Jul 01, 2009 11:00 pm

Re: PHP Random Float Help

Post 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.
The indelible lord of tl;dr
User avatar
KyleMassacre
Posts: 573
Joined: Wed Nov 27, 2013 12:42 pm

Re: PHP Random Float Help

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

Return to “Beginner Help and Support”