Reputation: 389
I want to make a script in PHP which displays the numbers and a hyphen between the numbers. It should look like this:
1-2-3-4-5-6-7-8-9-10
I have the following script right now, but the problem is it displays a hyphen at the end of the numbers:
$x = 1;
$h = 1;
while($x <= 10) {
echo "$x";
$x++;
if($h < $x){
echo "-";
$h++;
}
}
Thanks in advance :)
Upvotes: 2
Views: 2948
Reputation: 1353
This should solve the problem (I don't know why you use the h variable):
<?php
$x = 1;
$result="";
while($x <= 10) {
$result.=$x."-";
}
echo substr($result, 0,-1);
?>
or use the implode function
Upvotes: 0
Reputation: 21489
There is simpler way to do this work. Use range()
to create array contain numbers and use implode()
to join target array with string.
echo implode("-", range(1, 10));
See result in demo
Upvotes: 9
Reputation: 133360
You can use temp string
<?php
$x = 1;
$str ='';
while($x <= 10) {
if ($str == '') {
$str = $x;
} else {
$str = $str .'-'.$x;
}
}
echo $str;
?>
Upvotes: 0
Reputation: 6805
Insert the hypen before the number, except for the first number.
$x = 1;
while($x <= 10) {
if($x > 1)
echo '-';
echo $x;
$x++;
}
Upvotes: 1