Alex Alex - 2 years ago 79
PHP Question

How to split a string into an array, but rather chain new elements instead of adding an element per delimiter in php?

I know how to do that with a loop obviously, but I wonder if there was a one line for turning this:



[a, a/b, a/b/c, a/b/c/d]

Answer Source

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;
}, []);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download