Is there an easy way to get directory names without full path in Laravel?

201 Views Asked by At

I'm trying to get all folder names from a sub folder. I used the following :

$lang = File::directories('resources/lang/');

And the result looks like :

[
     "resources/lang/da",
     "resources/lang/de-CH",
     "resources/lang/de-ES",
     "resources/lang/en",
     "resources/lang/en-AE",
     "resources/lang/en-ES",
     "resources/lang/en-GB",
     "resources/lang/en-PT",
     "resources/lang/es",
     "resources/lang/es-PE",
     "resources/lang/fi",
     "resources/lang/fr",
     "resources/lang/fr-CH",
     "resources/lang/fr-ES",
     "resources/lang/it-CH",
     "resources/lang/nl",
     "resources/lang/no",
     "resources/lang/pt",
     "resources/lang/sk",
     "resources/lang/sv",
   ]

Is there a way to get only the folder names without the "resources/lang/" part ? (E.g : nl, no, pt, etc.)

2

There are 2 best solutions below

0
Lucas On BEST ANSWER

As the base directory is always the same, you can use array_map() to remove that part.

$lang = array_map(fn($value) => str_replace('resources/lang/', '', $value), $lang);
0
Bogdan On

You can use array_map with a standard PHP callback function named basename which does exactly that — returns trailing name component of path

$lang = array_map('basename', File::directories('resources/lang/'));

and the result looks like (works for every path not only 'resource/lang/')

[
 "da",
 "de-CH",
 "de-ES",
 "en",
 "en-AE",
 "en-ES",
 "en-GB",
 "en-PT",
 "es",
 "es-PE",
 "fi",
 "fr",
 "fr-CH",
 "fr-ES",
 "it-CH",
 "nl",
 "no",
 "pt",
 "sk",
 "sv",
]

@see https://www.php.net/manual/en/function.basename.php