Forest
Forest

Reputation: 938

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?

Upvotes: 5

Views: 493

Answers (7)

shivani parmar
shivani parmar

Reputation: 334

using array_slice and implode function

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

o/p

one
one-two
one-two-three

Upvotes: 1

Garry Welding
Garry Welding

Reputation: 3609

$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>";
  }
}

Upvotes: 2

Vasil Rashkov
Vasil Rashkov

Reputation: 1830

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

Upvotes: 3

A.L
A.L

Reputation: 10503

We can use array_shift() in order to extract the first element from the array. Then we can iterate over the values and append them to a 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 Codepad.

Upvotes: 2

deceze
deceze

Reputation: 522099

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

Upvotes: 6

B-and-P
B-and-P

Reputation: 1713

Another one:

$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>';
}

Upvotes: 2

Mihai Matei
Mihai Matei

Reputation: 24276

$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 />';
}

Upvotes: 3

Related Questions