What is the best approach to splitting a string into a multidimensional array in PHP while maintaining hierarchy?

When splitting a string into a multidimensional array in PHP while maintaining hierarchy, the best approach is to use a combination of explode() function and looping through the resulting array to build the multidimensional structure. By splitting the string based on a delimiter and then processing each part individually, you can maintain the hierarchy of the original string.

$string = "first|second|third|fourth";
$delimiter = "|";

$parts = explode($delimiter, $string);
$result = [];

$currentArray = &$result;

foreach ($parts as $part) {
    $currentArray[$part] = [];
    $currentArray = &$currentArray[$part];
}

print_r($result);