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?
Definition and Usage The basename() function returns the filename from a path.
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.
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.
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)?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With