-2

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. "-";
   }
}
nice_dev
  • 17,053
  • 2
  • 21
  • 35
Andrey
  • 63
  • 6
  • 2
    Tip: Print the `-` _before_ $x...unless it's the first one - which is much easier to detect than the last one. – ADyson Oct 26 '22 at 18:41
  • 1
    Try to use `break` after that condition, if you want the code to exit, that will stop the loop. You should dig into a php starting guide/lesson for such questions. Here a link for the reference: https://www.php.net/manual/en/control-structures.break.php – Gkiokan Oct 26 '22 at 18:42
  • 2
    You can [push them to an array](https://www.php.net/manual/en/function.array-push.php) and then use [implode()](https://www.php.net/manual/en/function.implode.php) with the `-` as glue. Just make sure you uncomment the code first (remove the `//`). Weird to have them in the posted code at all, tbh. – M. Eriksson Oct 26 '22 at 18:44

4 Answers4

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,",");
Max Pattern
  • 1,430
  • 7
  • 18
1

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;
   }
}
nice_dev
  • 17,053
  • 2
  • 21
  • 35
0

Turn the limit number into a variable and use a ternary operator to print out a dash only if $x + 1 < $limit

https://paiza.io/projects/EDj6-u-FAcYxYoR7ON_cvg

<?php

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

?>
symlink
  • 11,984
  • 7
  • 29
  • 50
0

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++;
}
Drk
  • 425
  • 2
  • 12