Linked Questions

Popular Questions

Split String Into Array and Append Prev Value

Asked by At

I have this string:

var/log/file.log

I eventually want to end up with an array looking like this:

Array => [
    '1' => 'var',
    '2' => 'var/log',
    '3' => 'var/log/file.log'
]

I currently have this:

<?php
    $string = 'var/log/file.log';
    $array = explode('/', $string);
    $output = [
        1 => $array[0],
        2 => $array[0]. '/' .$array[1],
        3 => $array[0]. '/' .$array[1]. '/' .$array[2]
    ];

    echo '<pre>'. print_r($output, 1) .'</pre>';

This feels really counter-intuitive and I'm not sure if there's already something built into PHP that can take care of this.

How do I build an array using appending previous value?

Related Questions