Burhan
Burhan

Reputation: 19

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

Upvotes: 1

Views: 1286

Answers (3)

Jeto
Jeto

Reputation: 14927

Here's a simple option using basename and dirname:

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

Demo

Upvotes: 4

Stuart
Stuart

Reputation: 6785

You could split the string on '/' and use array_pop to pop each item out of the resulting array:

$str = "Home/Gallery/Images/Mountains";
$bits = explode("/", $str);
// Gives: 
Array
(
  [0] => Home
  [1] => Gallery
  [2] => Images
  [3] => Mountains
)

$last = array_pop($bits);
echo 'last: ' .$last; // Mountains

$next = array_pop($bits);
echo 'next: ' .$next; // Images

Upvotes: 1

Montyroty
Montyroty

Reputation: 70

Just 2 small steps:

  1. Split by "/"
  2. Take last 2 items of the array
$path = "Home/Gallery/Images/Mountains";
$parts = explode("/", $path);
$folders = array_slice($parts, -2);

Then, you will have the two folders available in $folders array

I strongly recommend to read more about array_slice here: https://www.php.net/manual/en/function.array-slice.php

Upvotes: 1

Related Questions