skip to Main Content

Using while loop to print 10-20 odd numbers on the screen, with <-> (exapmle 11-13-15-17-19, <-> not after 19).How to take the last number so as not to put a -. Thank you.

<?php

$x = 10;
while($x < 20){
   $x++;
   if($x % 2){
      echo $x. "-";
   }
}

4

Answers


  1. You can push the odd values to an array and after the loop you can convert the array to a string with the implode (https://www.php.net/manual/en/function.implode.php) function.

    $x = 10;
    $arr = [];
    while($x<20){
      $x++;
      if ($x%2){
        $arr[] = $x;
      }
    }
    echo implode(",", $arr);
    // output will be a comma seperated string
    

    without (helper)array
    You can use rtrim() (https://www.php.net/manual/de/function.rtrim.php) funktion.

    $str = "1,2,3,";
    echo rtrim($str,",");
    
    Login or Signup to reply.
  2. As mentioned in the comments, have a boolean variable say firstTime. If this is true, don’t prepend a hyphen, else if it is false, prepend it with a hyphen.

    <?php
    
    $x = 10;
    $firstTime = true;
    while($x < 20){
       $x++;
       if($x % 2){
          echo ($firstTime ? "" : "-") . $x;
          $firstTime = false;
       }
    }
    
    Login or Signup to reply.
  3. Simple approach

    Imagine you are printing a list of numbers from 10 to 20. If it’s an even number, print the "-" symbol and if it’s odd number, print the number.

    <?php
    $start = 10;
    $end = 20;
    while($start<$end)
    {
      $n=$start;
      if($n>10)
      echo ($n%2==0)?"-":$n; //the gist is here
      $start++;
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search