In this article we will be studying how to find file extension in php. While coding in php or any other programming languages and dealing with the files, we may need to find out the file extension. There are several ways to find file extension in php. Some of the links for some sites are below:
One of the easiest way to find file extension in php is just a simple two line code. Consider the following code
<?php //Explode the file name with "." $explode = explode(".", $fileName); //Get the end array entery, and that is the file extension $extension = end($explode); ?>
You may know that the file extension in a file name is always at the end of the full file name and is separated from the file name by a dot (.). So first we need to explode the full file name by dot(.) which is done at line 4 in the above code.
Now as we know the explode function returns an array of strings which are all part of the exploded strings. As we mentioned above, the file extension is at the end of the full file name separated by a dot(.) from the file name, so the $explode array has the extension at the end of the array or the extension of the file is the last item of the $explode array.
Now we need to get that last item of the $explode array, which is done at line 7 using end function. What the end function do? the end function returns the last item of the target array and thats it. SO at line 7, the code returns the last item of the $explode array which is our desired file extension.
How easy that is to find file extension in php 🙂 .