Home > OS >  How can i write this as a while loop? PHP
How can i write this as a while loop? PHP

Time:07-26

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

CodePudding user response:

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

CodePudding user response:

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>';
    }
    
    ?>
  •  Tags:  
  • php
  • Related