Stream
Stream

Reputation: 67

Extract basename from filename in array

i have array with following strings. first im using explode "\n" and the output as below.

[1]=> string(121) "/Microsoft/Windows/Ravemp2300Handler/DeviceArrival/a.exe" 
[2]=> string(139) "/Microsoft/Windows/EventHandlers/Ravemp2300Arrival/b.exe" 
[3]=> string(89) "/Microsoft/Windows/DeviceHandlers/Rio600Handler/c.exe" 
[4]=> string(103) "/Microsoft/Windows/Rio600Handler/EventHandlers/d.exe" 

the following array will be extracted a.exe, b.exe and so on as below.

[1]=> string(121) "a.exe" 
[2]=> string(139) "b.exe" 
[3]=> string(89) "c.exe" 
[4]=> string(103) "d.exe" 

anyone have idea how to solve the problem? i really appreciate it. thank you in advance.

i got the solution, thanks to Leven and Emil Vikström for alternate solution.

$array2 = array_map('basename', $array1);

Upvotes: 3

Views: 4040

Answers (2)

Emil Vikström
Emil Vikström

Reputation: 91902

function lastPart($str) {
  return end(explode('/', $str));
}

$array2 = array_map('lastPart', $array1);

What this does is it applies the function lastPart to every element of the array. array_map is called a higher-order function because it takes another function as it's argument, which is a very common idiom in what is called functional programming. PHP is not functional but I still like this type of solutions.

array_filter and usort are two other higher-order functions well worth checking out.

For a more common imperative solution you may just run a foreach loop:

$array2 = array();
foreach($array1 as $value) {
  $array2[] = end(explode('/', $value));
}

Upvotes: 1

Leven
Leven

Reputation: 530

You're looking for basename():

$array2 = array_map('basename', $array1);

Upvotes: 10

Related Questions