I know you’ve probably seen this topic a hundred times, and so have I, but this one has a different twist. We already know that there are many ways to get the extension of a file, but which one is the fastest? That’s what I’m going to address right now.
Contenders
In each of the code examples $file
is set to c:\\xampplite\\htdocs\\index.php
.
String-to-Array Method
<?php
$ext = end(explode('.', $file));
echo $ext; // outputs 'php'
?>
Sub-String Method
<?php
$ext = substr($file, strrpos($file, '.')+1);
echo $ext; // outputs 'php'
?>
Path Info Method
<?php
$ext = pathinfo($file, PATHINFO_EXTENSION);
echo $ext; // outputs 'php'
?>
Setup
To test each of the contenders I put together a script that timed the execution of 1,000,000 iterations of each command. If you would like the script you can download it here.
Results
Sub-String Method: 0.778156 seconds
String-to-Array Method: 1.889744 seconds
Path Info Method: 2.020036 seconds
Winner
Our winner? The Sub-String Method! Next time you reach for that line of code to get a file’s extension, go for gold, and choose the Sub-String Method.
<?php
$ext = substr($file, strrpos($file, '.')+1);
echo $ext; // outputs 'php'
?>
Stan says
What if the filename is index.bak.php
Josh Hartman says
Well, the extension of that file would be
php
, so it would returnphp
.Martin says
Sub-String Method
if $file=’noextension’, $ext will be substr($file, 1), this does not work well
so things go like:
Josh Hartman says
Yes, if you know that you are working with file names that have no extension then modify it like so: