<?php
for ($i=0; $i<10; $i++) {
$number = mt_rand(1, 100);
if ($number %2== 0) {
$result = 'even';
} else {
$result = 'odd';
}
echo $number.' '.'('.$result.')'.'<br>';
}?>
I want to write it in a while loop form
this is as far as i have gotten. It just prints one random number and nothing else. I am using phpStorm and edge browser on PHP8.1.
<?php
$i=0;
while ($i<10) {
if ($number=mt_rand(1,100)) {
$result = 'even';
} else {
$result = 'odd';
}
$i++;
echo $number.' '.'('.$result.')'.'<br>';
}
?>
>Solution :
The main reason that the code is not working is that you are assigning the $number = mt_rand(1,100) inside the if() condition.
So everytime you execute if then it will not compare but it’ll keep assigning the $number variable. I have separated the assignment and comparison logic.
Try This:
<?php
$i=0;
while ($i<10) {
$number = mt_rand(1,100);
if ($number % 2 == 0) {
$result = 'even';
} else {
$result = 'odd';
}
$i++;
echo $number.' '.'('.$result.')'.'<br>';
}