Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Building increasingly long strings from an array

Tags:

arrays

string

php

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?

like image 566
Forest Avatar asked Feb 26 '16 12:02

Forest


People also ask

How do you convert an array to a string?

So how to convert String array to String in java. We can use Arrays. toString method that invoke the toString() method on individual elements and use StringBuilder to create String.

Can we make a NumPy array of strings?

The elements of a NumPy array, or simply an array, are usually numbers, but can also be boolians, strings, or other objects. When the elements are numbers, they must all be of the same type. For example, they might be all integers or all floating point numbers.


1 Answers

for ($i = 1, $length = count($array); $i <= $length; $i++) {
    echo join('-', array_slice($array, 0, $i)), PHP_EOL;
}
like image 153
deceze Avatar answered Sep 24 '22 10:09

deceze