Does anyone have a brilliant idea how to obtain the elements with the deepest path from an array with file paths? If this sounds weird, imagine the following array:
/a/b
/a
/1/2/3/4
/1/2
/1/2/3/5
/a/b/c/d/e
What I want to obtain is:
/1/2/3/4
/1/2/3/5
/a/b/c/d/e
Wondering what the fastest method is without having to iterate over the whole array over and over again. Language is PHP (5.2).
Following your clarifications, here’s a function that would do it. It keeps an array of the “deepest paths” found and compares each path against it. The best-case scenario is O(n) (if all paths are subpaths of the largest one) and worst-case scenario is O(n2) (if all paths are completely distinct).
Note that
continue 2means “continue on the outer loop”.If your folder names don’t end with slashes, you’ll want to do an additional check in the two
ifs: that the character next to the prefix in the deeper path is a slash, because otherwise a path like/foo/barwill be seen as a “deeper path” than/foo/b(and will replace it).