Reputation: 10216
I know how to do that with a loop obviously, but I wonder if there was a one line for turning this:
a/b/c/d
into
[a, a/b, a/b/c, a/b/c/d]
Upvotes: 1
Views: 88
Reputation: 1657
Not a one-liner exactly, but you can do this with array_reduce:
$arr = array_reduce(explode('/', 'a/b/c/d'), function($accumulator, $char) {
$prev = empty($accumulator) ? '' : $accumulator[count($accumulator)-1] . '/';
$accumulator[] = $prev.$char;
return $accumulator;
}, []);
Upvotes: 3
Reputation: 40861
has a semi-colon in the closure, so I guess it's technically a two-liner
echo json_encode(array_map(function($val,&$accumulator){return $accumulator=$accumulator.$val; },explode('/','a/b/c/d'),array()));
Results in this:
["a","ab","abc","abcd"]
Upvotes: 0