## ProgrammingPHP For Loops guidance needed?Posted: Fri Aug 11, 2017 9:00 am

Status: Offline
Joined: Mar 01, 20117 Year Member
Posts: 353
Reputation Power: 24
 Hello everyone, I am fairly new to PHP and I am trying to solve this problem where I need to make a for loop to generate 10 random numbers from the range (1,20) and then output whether they are odd or even. I am so stuck on this though. So far I have this below, but I know its wrong somewhere. Any help or guidance would be much appreciated. ``` \$rand120 = rand(1, 20);     for(\$rand120 = 10; \$rand120 <= 20; \$rand120++);     {         echo "\$rand120"."
";     } if (\$rand120 % 2 === 0) {    echo "\$rand120 is even
"; } else {    echo "\$rand120 is odd
"; } ```
#2. Posted:
PeakModz
• Christmas!
Status: Offline
Joined: Nov 29, 20116 Year Member
Posts: 141
Reputation Power: 8
 ``` for(\$i = 0; \$i < 10;\$i++){    \$randInt = rand(1,20);    if((\$randInt % 2) == 0){       echo \$randInt." is even
";    }else{       echo \$randInt." is odd
";    } } ``` Hopefully, this is what you're looking for. Output: 3 is odd 2 is even 18 is even 4 is even 6 is even 15 is odd 13 is odd 7 is odd 12 is even 8 is even 11 is odd
#3. Posted:
Xaldin
• 2 Million
Status: Offline
Joined: Oct 09, 20107 Year Member
Posts: 2,272
Reputation Power: 102
 ^^ is correct but ill explain a little why yours is wrong. Youre assigning \$rand120 a random number which is good but its outside of your loop so its only getting the value once when you need 10 of them also youre overwriting the random number with your for statement ``` \$rand120 = rand(1, 20);     for(\$rand120 = 10; \$rand120 <= 20; \$rand120++);     {         echo "\$rand120"."
";     } ``` The first line giving it lets say a value of 17 and the the second line for(...) gives it 10 no matter what. In the above solution a loop using a counter variable \$i is what you were looking for its generally what you will use if you want to run through something X amount of times (you want 10 numbers) Your If Else statement is decent but it would need to be inside the loop like in the above example because you want to check each of the ten numbers for odd or even, === isnt really needed either == is fine. Hopefully I helped explain Peak's solution a little.
#4. Posted:
Cyimking
• E3 2016
Status: Offline
Joined: May 02, 20125 Year Member
Posts: 1,104
Reputation Power: 33
 Here's my take: 1. ```
Users browsing this topic: None