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. "-";
}
}
CodePudding user response:
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;
}
}
CodePudding user response:
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
CodePudding user response:
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. "-";
}
}
?>
CodePudding user response:
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 ;
}