user3740970 user3740970 - 1 month ago 11
PHP Question

How to insert a hyphen between numbers in PHP?

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 :)

Answer

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