0
\$\begingroup\$

I have written a function that retrieves the extension from a given file name for you. I would like to make this more efficient and increase it's performance.

<?php
function getExt($filename) {
    //if(!is_file($filename)) return '';
    $n = strlen($filename);
    if($n<2) return '';
    $non_ext = '';
    $ext = '';
    for($i=$n;$i--;$i>=1) {
        $c = $filename[$i];
        if($c==='.') {
            $ext = '.'.$non_ext.$ext;
            $non_ext = '';
        }else
            $non_ext = $c.$non_ext;
    }
    return $ext;
}
$filename = "asdfasdfasd.tar.gz";
$ext = getExt($filename);
var_dump($ext);
?>
\$\endgroup\$
  • 1
    \$\begingroup\$ You need only one line of code while Php PATHINFO_EXT already did the function: $ext = pathinfo($filename, PATHINFO_EXTENSION); \$\endgroup\$ – Huy Trịnh Jul 3 '17 at 9:35
  • 1
    \$\begingroup\$ $ext = pathinfo($path, PATHINFO_EXTENSION); Dont try reinventing the wheel. Instead Read The Manual \$\endgroup\$ – RiggsFolly Jul 3 '17 at 9:35
  • 1
    \$\begingroup\$ Small but possibly relevant note Your function does not provide the extension, it provides everything after the first DOT in the filename. People use dots in filenames all the time. \$\endgroup\$ – RiggsFolly Jul 3 '17 at 9:41
  • \$\begingroup\$ This line gives the exact same output as your function, meaning "after first dot". Var_dump(explode(".", $filename, 2)[1]); 3v4l.org/3rj1g \$\endgroup\$ – Andreas Jul 3 '17 at 9:57
  • \$\begingroup\$ @Andreas Ahhh you are right. \$\endgroup\$ – Suriya Keng Kaewmungmuang Jul 3 '17 at 10:13
1
\$\begingroup\$

You can use PHP inbuilt function. Inbuilt functions are the fastest.

$ext = pathinfo($filename, PATHINFO_EXTENSION);
| improve this answer | |
\$\endgroup\$
  • \$\begingroup\$ I think this has been quite adequately covered in comments \$\endgroup\$ – RiggsFolly Jul 3 '17 at 9:38
  • \$\begingroup\$ You cannot get more than one dot sign in extension from file by this PHP built-in function, but you can get that with my function. But my function is mistake some thing, I have to comment out this line //if(!is_file($filename)) return ''; \$\endgroup\$ – Suriya Keng Kaewmungmuang Jul 3 '17 at 9:43
0
\$\begingroup\$

I like this method suggess by @Andreas

$filename = "asdfasdfasdgz";
var_dump(@explode(".", $filename, 2)[1]);
| improve this answer | |
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.