Reputation: 11
$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
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
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);
Upvotes: 0
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.
Upvotes: 0