Search code examples
phppathsubstr

How to get last & second last folder name from path using php?


Path:

Home/Gallery/Images/Mountains

Last folder name in this path is Mountains and second last folder name is Images.


I want to show this output:

Last folder: Mountains
Second last folder: Images

Is it possible with substr or any another way. Anyone here who can give me answer? Thanks


Solution

  • Here's a simple option using basename and dirname:

    $path = 'Home/Gallery/Images/Mountains';
    $lastFolder = basename($path);
    $secondToLastFolder = basename(dirname($path));
    

    Demo