1

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]

2 Answers 2

3

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

2 Comments

this returns aababcabcd which is correct for the original question, but I need to include the /s, so $accumulator[] = $prev . $char . '/'; seems right but it also adds an / to the end. any idea?
In that case you want to define $prev as having a trailing slash, if it's not empty. See edited answer.
0

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"]

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.