Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Which function is better suited to retrieve the basename of a file in PHP: basename or pathinfo? [closed]

Tags:

string

file

php

What's the recommended way of grabbing the basename (file name without extension) of a file in PHP?

echo basename('foo.jpg', '.jpg');
// outputs "foo"

echo pathinfo('foo.jpg', PATHINFO_FILENAME);
// outputs "foo"

Apparently both produce the same output. What are the advantages of using one over the other?

Performance wise it looks like basename() is faster by approximately 300ms over 1,000,000 iterations:

<?php

$f = 'foo.jpg';
$n = 1000000;

$start = microtime(true);

for ($i = 0; $i < $n; $i++) {
    basename($f);
}

$stop1 = microtime(true);

for ($i = 0; $i < $n; $i++) {
    pathinfo($f, PATHINFO_FILENAME);
}

$stop2 = microtime(true);

echo "Basename result: " . ($stop1 - $start) . " seconds\n";
echo "Pathinfo result: " . ($stop2 - $stop1) . " seconds\n";

This outputs:

Basename result: 1.0358278751373 seconds
Pathinfo result: 1.3277871608734 seconds

Besides the marginal performance gains, I'm also interested on how are these functions implemented behind the scenes? Is the underlying algorithm for retrieving the basename similar in both cases?

like image 694
ukliviu Avatar asked Sep 06 '13 16:09

ukliviu


People also ask

What does basename function do in PHP?

Definition and Usage The basename() function returns the filename from a path.

What does Pathinfo do in PHP?

The pathinfo() is an inbuilt function which is used to return information about a path using an associative array or a string. The returned array or string contains the following information: Directory name. Basename.

What is base name of file?

The basename is the final rightmost segment of the file path; it is usually a file, but can also be a directory name. Note: FILE_BASENAME operates on strings based strictly on their syntax. The Path argument need not refer to actual or existing files.


1 Answers

If you only want the basename, then use the basename function. As always in any case, try to use the less consuming operation; why to create an array of info you won't need (using pathinfo) when you can get what you want in a string directly (with basename function)?

like image 63
rodripf Avatar answered Oct 15 '22 00:10

rodripf