Split String Into Array and Append Prev Value

You could do something like this with a foreach

<?php
$string = 'var/log/file.log';
$array = explode('/', $string);

$last = '';
$output = array();
foreach ($array as $key => $value) {
    $result = $last.$value;
    $output[$key] = $result;
    $last = $result.'/';
}

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

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.


<?php
$string = 'var/log/some/other/directory/file.log';
$array = explode('/', $string);

$i = 0;
foreach ($array as $data) {
    $output[] = isset($output) ? $output[$i - 1] . '/' . $data : $data;
    $i++;
}


echo '<pre>';

print_r($output);

A simpler solution is above. You simple set your new array field to be a concatenation of your previous one from your new array and the current one from your foreach.

Output is:

Array
(
    [0] => var
    [1] => var/log
    [2] => var/log/some
    [3] => var/log/some/other
    [4] => var/log/some/other/directory
    [5] => var/log/some/other/directory/file.log
)