简体   繁体   中英

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>';
}
    
?>

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>';
    }

i changed to 10 to make case: the script you use can generate numbers can repeat; the second script i put generates unique random numbers(in case you need); by uncomment //$max=100; and commenting $max=10; the second script will generate UNIQUE NUMBERS in range 1..100

  <?php


/*the first script*/    
    $max=100;
    //$max=10;
    
    
    $i=0;
    while ($i<10) {
      if (($number=mt_rand(1,$max))and(($number % 2) ==0)) {
        $result = 'even';
      } else {
        $result = 'odd';
      }
      $i++;
      echo $number.' '.'('.$result.')'.'<br>';
    }
      
    echo '<hr>';
        
    /*the second script : unique numbers*/
    $nrs=range(1,$max);
    $i=-1;while($i++<9){
        $pos=mt_rand(0,count($nrs)-1);
        $nr=$nrs[$pos];
        unset($nrs[$pos]);
        rsort($nrs);
        echo $nr.'-'.(($nr%2)==0?'even':'odd').'<br>';
    }
    
    ?>

i did this: 解决方案同时扣

Please, check me if my answer help you. Cheers

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM