March 26, 2012

adding previous array values to newer array values

Question by steve

$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.

Answer by Starx

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

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!