Calculating + random function

Hello guys, I was wondering if what I came up with is correct.
Basically the first function divides $x by $y and the second uses first function 10 times, but with random arguments.

[php]<?php
function divide($x, $y) {
$z = $x / $y;
return “$z”;
}
function randrepeat() {
divide(rand[$x, $y]);
$start = 0;
$stop = 10;
while ($start++ < $stop);
}
?>[/php]

I’d appreciate any help! :slight_smile:

I don’t really understand what it is you are trying to achieve. You are making a division and then randomising the output of that division. If you want a random number, just generate a random number?

Like stated already don’t know what you are trying to do, but I would do something like this to learn functions, loops and random numbers.

[php]<?php
$dice = [];
function dice($min, $max) {
$roll = rand($min, $max);
return $roll;
}
$min = 1;
$max = 6;

for ( $i=0; $i<2; $i++) {
$dice[$i] = dice($min, $max);
}

//echo “

” . print_r($dice, 1) . “
\n”;

$total = $dice[0] + $dice[1];

echo "Dice Number One = " . $dice[0] . " and Dice Number Two = " . $dice[1] . " for a Total of " . $total . “
\n”; [/php]

Just playing around with this script or creating your own randomize script with a little logic behind it can be fun and learning at the same time. One thing that I do is try to name my variables/functions/classes that are meaningful in a script, sometimes it can be a little tricky coming up with an appropriate name(s). However that is where find and replace comes in handy in most IDE when the appropriate name comes into your head. :slight_smile:

I’m just trying to make a function within function, so that I can use either of them later on. I agree that my naming might confuse me later on, however the primary thing I wanted to focus on is whether the original code I posted would work (no errors etc).

Well, hardanger, both of the answers gave you hints on how to do it, but, your biggest issue was that
you did your call to the “divide” routine BEFORE you started your while loop. You need to move your
call to the function in line to inside your WHILE loop. BUT, you also do not start or end your WHILE loop.

SO…
[php]

<?php function divide($x, $y) { $z = $x / $y; return "$z"; } function randrepeat() { $start = 0; $stop = 10; while ($start++ < $stop); echo divide(rand[$x, $y]); } } ?>

[/php]
There were no errors because each command is valid. But, you did not display anything. But, I would use
Strider64’s sample because a FOR would be better than a WHILE for this type of routine. Since you might
be a student, I would start with this link. It explains FOR’s and you can select the link on the left side of
the page to look at WHILE’s and FUNCTION’s, too. Hope it helps…
http://www.w3schools.com/php/php_looping_for.asp

Sponsor our Newsletter | Privacy Policy | Terms of Service