Take the 2-minute tour ×

I've seen alot of functions which handle the retrival of an extension of a particular filename. I, myself, always use this solution of mine:

function extension( $filename = __FILE__ ) {
    return (strtolower($parts[(sizeof($parts) - 1)]));

echo extension();              // php
echo extension('.htaccess');   // htaccess
echo extension('htaccess');    // htaccess
echo extension('index.php');   // php

Is that the best and the fastest approach?

share|improve this question
pathinfo() php.net/manual/en/function.pathinfo.php with PATHINFO_EXTENSION –  Mark Baker Mar 6 '13 at 21:41
possible duplicate of How to extract a file extension in PHP? –  John Conde Mar 6 '13 at 21:44
add comment

4 Answers

I'll go ahead and say that it is not the best approach, and I suspect it isn't fastest either. The canonical way is using pathinfo.

$ext = pathinfo($file, PATHINFO_EXTENSION);

The problem with using explode is that you're creating an array, which necessarily takes up more memory (even if it is a trivial amount) which almost always leads to a decrease in speed. If you really want to go with a home-cooked non-canonical way, I suggest strrpos:

function get_extension($file)
    $pos = strrpos($file, '.');
    // for condition when strrpos returns FALSE on failure.
    if($pos !== FALSE) return substr($file, $pos);
    return FALSE;
share|improve this answer
yes, you are right! thank you, and your solution helps alot! :) –  user1386320 Mar 6 '13 at 21:47
add comment

Just use pathinfo()

$file =  pathinfo('index.php');
echo $file['extension']; // 'php'
share|improve this answer
add comment

That works, one thing i would change is your return:

return strtolower(end($parts));

I agree pathinfo is probably the better way I was just improving your code.

share|improve this answer
add comment
$file = "filename.php.jpg.exe";
echo substr($file, strrpos($file, "."));//.exe
share|improve this answer
with the dot as a prefix? –  user1386320 Mar 6 '13 at 21:53
substr($file, strrpos($file, ".")+1); for removing dot –  user1646111 Mar 6 '13 at 21:55
isn't my function a bit easier... :) –  user1386320 Mar 6 '13 at 21:56
as you like, there are many option for you to select one :) –  user1646111 Mar 6 '13 at 22:05
one up for you, for your effort! :) –  user1386320 Mar 6 '13 at 22:06
add comment

Your Answer

