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

1
  • Which language is that? Please retag if I was wrong, but there was no statement about it in the question. stackoverflow.com/questions/how-to-ask Commented Mar 26, 2012 at 12:24

3 Answers 3

1

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++;
}
Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.