Creating longer strings from an array

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

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

And repeat the following lines:

 one one-two one-two-three 

I can’t figure out how to do this. I tried using a variable to save the previous one and then using it, but it only works for one thing:

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

Withdrawal:

 one two two-three 

This approach is likely to be ineffective anyway, since this script should technically be able to handle any length of the array.

Does anyone help?

+5
source share
7 answers
 for ($i = 1, $length = count($array); $i <= $length; $i++) { echo join('-', array_slice($array, 0, $i)), PHP_EOL; } 
+6
source
 $arr = array('one', 'two', 'three'); foreach (array_keys($arr) as $index) { $result = array(); foreach ($arr as $key => $val) { if ($key <= $index) { $result[] = $val; } } echo implode('-', $result) . '<br />'; } 
+3
source

You are comparing 0! = Null, the problem arises from comparing with only one =, try! ==, it should work.

+3
source

Other:

 $data = array('one','two','three'); $str = ''; $len = count($data); for ($i=0; $i<$len;$i++){ $delim = ($i > 0) ? '-' : ''; $str .= $delim . $data[$i]; echo $str .'<br>'; } 
+2
source

We can use array_shift() to extract the first element from the array. Then we can iterate over the values ​​and add them to the string:

 <?php $array = array( 'one', 'two', 'three' ); // Get the first element from the array (it will be removed from the array) $string = array_shift($array); echo $string."\n"; foreach ($array as $word) { $string = implode('-', array($string, $word)); echo $string."\n"; } 

Output:

 one one-two one-two-three 

Demo in the code .

+2
source
 $arr = ['one','two','three']; doSomething($arr); function doSomething($arr) { foreach($arr as $key=>$val) { $s = array_slice($arr,0,($key+1)); echo implode('-',$s) . "<br>"; } } 
+2
source

using array_slice and implode

 foreach($arr as $key => $value){ echo implode("-",array_slice($arr, 0, $key+1))."<br/>"; } 

o / r

 one one-two one-two-three 
+1
source

Source: https://habr.com/ru/post/1243939/


All Articles