Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 581
treyBake Avatar asked Jan 25 '19 09:01

treyBake


People also ask

How do you split a string into an array?

The split() method splits a string into an array of substrings. The split() method returns the new array. The split() method does not change the original string. If (" ") is used as separator, the string is split between words.

Which method can you use character other than comma to separate values from array?

In that case, the split() method returns an array with the entire string as an element. In the example below, the message string doesn't have a comma (,) character.

How do you split the last element?

To split a string and get the last element of the array, call the split() method on the string, passing it the separator as a parameter, and then call the pop() method on the array, e.g. str. split(','). pop() . The pop() method will return the last element from the split string array.


4 Answers

<?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
)
like image 69
pr1nc3 Avatar answered Oct 28 '22 18:10

pr1nc3


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.

like image 27
Tim Biegeleisen Avatar answered Oct 28 '22 18:10

Tim Biegeleisen


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>';
like image 4
Oliver Nybo Avatar answered Oct 28 '22 17:10

Oliver Nybo


You can get parent directory in a loop and add it to output variable. For example with help the following algorithm:

$path = 'var/log/file.log';
$output = [];

$pos = strlen($path);
while ($pos !== false) {
    $path = substr($path, 0, $pos);
    array_unshift($output, $path);
    $pos = strrpos($path, DIRECTORY_SEPARATOR);
}

or with dirname() function

$path = 'var/log/file.log';
$output = [];

do {
  array_unshift($output, $path);
  $path = dirname($path);
} while ($path !== '.');

Also, you can work with $path string as an array of chars and find directory separator in it:

$path = 'var/log/file.log';
$output = [];

$tmp = '';
$len = strrpos($path, DIRECTORY_SEPARATOR); // you can use strlen instead of strrpos,
                                            // but it'll look over filename also
for ($i = 0; $i < $len; $i++) {        
    if ($path[$i] === DIRECTORY_SEPARATOR) {
        $output[] = $tmp;
    }
    $tmp .= $path[$i];
}
$output[] = $path;

but keep in mind you couldn't use this way if $path string has multibyte encoding

The result of all methods will be:

Array (
     [0] => var
     [1] => var/log
     [2] => var/log/file.log 
)
like image 4
Maksym Fedorov Avatar answered Oct 28 '22 18:10

Maksym Fedorov