Furze Furze - 6 months ago 18
PHP Question

Building increasingly long strings from an array

I am writing a PHP function that will take an array in the following format:

array(
'one',
'two',
'three'
)


And echo the following strings:

one
one-two
one-two-three


I can't figure out how to do this. I've tried using a variable to store the previous one and then use it, but it only works for one:

$previous = null;
for($i = 0; $i < count($list); $i++) {
echo ($previous != null ? $route[$previous] . "-" : '') . $route[$i];
$previous = $i;
}


Outputting:

one
two
two-three


That approach would probably be inefficient anyway, as this script should technically be able to handle any length of array.

Can anybody help?

Answer
for ($i = 1, $length = count($array); $i <= $length; $i++) {
    echo join('-', array_slice($array, 0, $i)), PHP_EOL;
}