Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can i write this as a while loop? PHP

<?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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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>';
    }
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading