rand() function not working as expected (nested within foreach())?
The idea is that a max and a minimum value are posted, and then a random number between the two is generated.
For example, $mins = array(30,40,50,60)
and $maxs = array(40,50,60,70)
, and then my code:
foreach($mins as $minkey => $maxval) {
foreach($maxs as $maxkey => $maxval) {
$hits[$maxkey] = rand($minval,$maxval);
}
}
If I then var_dump($mins)
, var_dump($maxs)
and var_dump($hits)
, I get:
array(4) { [1]=> string(2) "30" [2]=> string(2) "40" [3]=> string(2) "50" [4]=> string(2) "60" } array(4) { [1]=> string(2) "40" [2]=> string(2) "50" [3]=> string(2) "60" [4]=> string(2) "70" } array(4) { [1]=> int(27) [2]=> int(36) [3]=> int(19) [4]=> int(41) }
I thought the fact that $maxs
and $mins
contained string values, while $hits
containing integers (i.e. rand()
requires intege开发者_高级运维r inputs ?) might be the issue so I updated my loop to become:
foreach($mins as $minkey => $minval) {
foreach($maxs as $maxkey => $maxval) {
$minval = (int)$minval;
$maxval = (int)$maxval;
$hits[$maxkey] = rand($minval,$maxval);
}
}
But on var_dump($mins)
, var_dump($maxs)
and var_dump($hits)
, this was dumped:
array(4) { [1]=> string(2) "30" [2]=> string(2) "40" [3]=> string(2) "50" [4]=> string(2) "60" } array(4) { [1]=> string(2) "40" [2]=> string(2) "50" [3]=> string(2) "60" [4]=> string(2) "70" } array(4) { [1]=> int(0) [2]=> int(47) [3]=> int(0) [4]=> int(55) }
Does anyone have any idea why this isn't working as expected?
Any thoughts/answers/comments would be very much appreciated :)!
Do you want to do that? if yes, you can't have one loop in another...
for($i = 1; $i <= sizeof($mins); $i++) {
$hits[$i] = rand($mins[$i], $maxs[$i]);
}
For one you're overwriting your variables:
foreach($mins as $minkey => $maxval) {
foreach($maxs as $maxkey => $maxval) {
$hits[$maxkey] = rand($minval,$maxval);
}
}
I'm assuming is supposed to be:
foreach($mins as $minkey => $minval) {
foreach($maxs as $maxkey => $maxval) {
$hits[$maxkey] = rand($minval,$maxval);
}
}
Don't know what the expected result is but try this :
for ($i=0, $len = count($mins); $i < $len; $i++) {
$hits[$i] = rand($mins[$i], $maxs[$i]);
}
It looks like you've got a typo with your first foreach loop, it should be
foreach($mins as $minkey => $minval)
This is causing an E_NOTICE error to be thrown and also prevents rand from working since minval doesn't exist. It's always a good idea to have error_reporting set to show notices in development which you can easily do via adding this at the start of your code:
error_reporting(E_ALL);
See php error reporting for more information
精彩评论