PHP Array Exercises : Extension of a file
32. Get File Extension
Write a PHP program to get the extension of a file.
Sample Solution:
PHP Code:
<?php
// Define a function named file_extension that takes a file path as an argument
function file_extension($str1){
// Replace backslashes with an empty string in the given path
$str1 = implode("", explode("\\", $str1));
// Explode the path using the dot as a delimiter to extract the file extension
$str1 = explode(".", $str1);
// Convert the file extension to lowercase and return it
$str1 = strtolower(end($str1));
return $str1;
}
// Define a file path 'example.txt'
$file = 'example.txt';
// Call the file_extension function and display the result
echo "\n" . file_extension($file) . "\n";
?>
Output:
txt
Flowchart:

For more Practice: Solve these Related Problems:
- Write a PHP function to extract and return the file extension from a given filename string.
- Write a PHP script to parse a file path and output the extension after validating its format.
- Write a PHP program to implement a regular expression that matches and displays the extension of a file.
- Write a PHP function to handle cases with multiple dots in a filename and return the last segment as the extension.
Go to:
PREV : Get Index of Highest Value in Associative Array.
NEXT : Search Value Within Associative Array.
PHP Code Editor:
Contribute your code and comments through Disqus.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.