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.

PHP Random Float Help

Postby Fireal » Sun May 21, 2017 1:16 pm

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
Fireal
 
Posts: 11
Joined: Sun May 21, 2017 12:51 pm
Has thanked: 5 times
Been thanked: 0 time

Re: PHP Random Float Help

Postby Jackolantern » Sun May 21, 2017 10:05 pm

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
Jackolantern
 
Posts: 10893
Joined: Wed Jul 01, 2009 6:00 pm
Location: Houston, TX
Has thanked: 22 times
Been thanked: 92 times
Blog: View Blog (1)

Re: PHP Random Float Help

Postby KyleMassacre » Mon May 22, 2017 6:48 pm

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
Skype: KyleMassacre
My NWE Modules
User avatar
KyleMassacre
 
Posts: 572
Joined: Wed Nov 27, 2013 7:42 am
Has thanked: 19 times
Been thanked: 36 times


Return to Beginner Help and Support

Who is online

Users browsing this forum: No registered users and 1 guest

cron

x