steve
steve

Reputation: 11

adding previous array values to newer array values

$test = 'test1/test2/test3/test4';

I am trying to get a array from that $test above which i'd like to output like below.

Array
(
    [0] => /
    [1] => /test1/
    [2] => /test1/test2/
    [3] => /test1/test2/test3/
    [4] => /test1/test2/test3/test4/
)

I've tried loops but can't quite figure out how to get it quite right.

Upvotes: 1

Views: 55

Answers (3)

Vik
Vik

Reputation: 5961

Try to make loop like :

$test = 'test1/test2/test3/test4';
$test_arr = explode("/", $test);
$test_size = count($test_arr);
$count = 1;
$new_test_arr = array('/');
for ($i=0; $i<$test_size; $i++)
{
  $new_test_arr[$count] = $new_test_arr[$i] . $test_arr[$i] . "/"
  $count++;
}

Upvotes: 1

Starx
Starx

Reputation: 78971

A very easy and simple way, for this case would be

$test = 'test1/test2/test3/test4';
$arr = explode("/", $test);

$t = "";
$newArray = array("/");
foreach($arr as $value) {
   $t .= "/".$value;
   $newArray[] = $t;
}

print_r($newArray);

Demo

Upvotes: 0

Jon
Jon

Reputation: 437366

Here's a way to do it very compactly:

$parts = explode("/", $test);
for($i = 0; $i <= count($parts); ++$i) {
    echo "/".implode("/", array_slice($parts, 0, $i))."\n";
}

Not terribly efficient, but I don't think efficiency would matter in something trivial you 'd only do once. On the plus side, the loop modifies no variables which makes it easier to reason about.

See it in action.

Upvotes: 0

Related Questions