# Give function get file extension for you

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); ?>  • You need only one line of code while Php PATHINFO_EXT already did the function: $ext = pathinfo($filename, PATHINFO_EXTENSION); – Huy Trịnh Jul 3 '17 at 9:35 • $ext = pathinfo($path, PATHINFO_EXTENSION); Dont try reinventing the wheel. Instead Read The Manual Jul 3 '17 at 9:35 • 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. Jul 3 '17 at 9:41 • This line gives the exact same output as your function, meaning "after first dot". Var_dump(explode(".",$filename, 2)[1]); 3v4l.org/3rj1g Jul 3 '17 at 9:57
• @Andreas Ahhh you are right. Jul 3 '17 at 10:13

$ext = pathinfo($filename, PATHINFO_EXTENSION);

• 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 ''; Jul 3 '17 at 9:43 I like this method suggess by @Andreas $filename = "asdfasdfasdgz";