I want to get an array of immediate sub-directories based on the current path from a given list of paths. Here is an example list of paths and the desired result:
$dirs = [
'/chris',
'/chris/usa',
'/david',
'/',
'/chris/canada/2022',
'/david/uk',
];
$current_path = "/chris";
// Required result:
$sub_dirs = ['/usa', '/canada'];
The current path could be anything from /
to the last sub directory, in which case I would end up with an empty $sub_dirs
.
My best attempt at it is this:
$dirs = [
'/chris',
'/chris/usa',
'/david',
'/',
'/chris/canada/2022',
'/david/uk',
];
$sub_dirs = [];
$current_path = "/";
foreach($dirs as $dir){
if(strstr($dir, $current_path)){
$sub_dirs[] = str_replace($current_path, '', $dir);
}
}
The above fails at two things. If the $current_path = "/"
then the returned array is just paths without slashes since I strip them out with strstr()
and if the $current_path = "/chris"
then I still get the sub-directories.
How should I correctly solve it?
Thank you!
3
Answers
/chris/
to get only sub directories.explode()
, and get the first.str_starts_with()
Output
I like the approach of creating a tree out of the paths (adapted from this answer).
Then it’s easier to get the children based on a path.
Output:
I feel like I have a bit shorter answer than the previous ones, but not sure if it’s the most efficient one though.