2 Methods for Finding File Extensions in PHP

2 Methods for Finding File Extensions in PHP

Two very simple methods for getting to know which is the file extension of the file, using two very simple PHP functions.

1. Method: function end

The end function finds the last member of an array. So if we want to get the file extension, we will first explode our filename at the dots (.) and then use this function to get the last array object, which will obviouly be the extension.

Example:

<?php
$file = 'something.jpg';
$explode = explode(".", $file);
echo end($explode); // will return jpg
?>

Or shortened:

<?php
$file = 'something.jpg';
echo end(explode(".", $file)); // will return jpg
?>

2. Method: function strrchr

This function finds the last occurrence of a character in a string. Using this function, our php code would look like this:

<?php
$file = 'something.jpg';
echo substr(strrchr($file,"."),1);
?>

Easy!

If you liked this post think about subscribing to my RSS feed and prevent missing anything interesting. It's free, fast and doesn't hurt. Promise. Click here.
Related posts: