$random = rand(0,10); if (($random > 0) && ($random < 5)) { some function } if (($random > 5) && ($random < 7)) { some function } if (($random > 7) && ($random < 11)) { some function } echo $random; PHP: If 0,5 or 7 come out, my function for that number wont function, does anybody know what I'm doing wrong ? Would I better of writing 10 functions ? if ($random_number == 1) { some function } elseif ($random_number == 2) { some function} elseif ($random_number == 3) { some function} elseif ($random_number == 4) { some function} etc...
Using the equal sign like this $random = rand(0,10); if (($random >= 0) && ($random < 5)) { //0 to 4 } if (($random >= 5) && ($random < 7)) { //5 to 6 } if (($random >= 7) && ($random < 11)) { //7 to 10 } echo $random; PHP:
First of all, I'd use mt_rand() instead of rand(). It's slightly faster and yields better "randomness". As for the if blocks, when it gets to be 3 or more, I general start looking at using switch/case. Particularly in your case, because I can see you needing to add additional cases over time. It's just easier to follow the flow (and update if necessary). That's just my opinion, though. As for the code, I'd do this: $intRandom = mt_rand(0, 10); switch (true) { case ($intRandom >= 0 && $intRandom < 5) : // some function break; case ($intRandom >= 5 && $intRandom < 7) : // some function break; case ($intRandom >= 7 && $intRandom < 11) : // some function break; } print($intRandom); Code (markup):