Search code examples
phparraysexplode

Split String Into Array and Append Prev Value


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?


Solution

  • This solution takes the approach of starting with your input path, and then removing a path one by one, adding the remaining input to an array at each step. Then, we reverse the array as a final step to generate the output you want.

    $input = "var/log/file.log";
    $array = [];
    while (preg_match("/\//i", $input)) {
        array_push($array, $input);
        $input = preg_replace("/\/[^\/]+$/", "", $input);
        echo $input;
    }
    array_push($array, $input);
    $array = array_reverse($array);
    print_r($array);
    
    Array
    (
        [0] => var
        [1] => var/log
        [2] => var/log/file.log
    )
    

    The above call to preg_replace strips off the final path of the input string, including the forward slash. This is repeated until there is only one final path component left. Then, we add that last component to the same array.