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
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.
without (helper)array
You can use
rtrim()
(https://www.php.net/manual/de/function.rtrim.php) funktion.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.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
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.