Life of a web developer

November 23, 2010

Tutorial: getExt() – Get the extension of a file

Filed under: PHP, Tutorials — Tags: , , — Ole Aass @ 6:56 pm

This is probably the shortest function you can make that’s still very usefull

function getExt($filename) {
    return end(explode('.', $filename));
}

A more advanced version of this function will handle an array of filenames

function getExt($filenames) {

    // Make sure the variable is an array
    if (!is_array($filenames)) {
        $filenames = (array) $filenames;
    }

    // Loop through the array and assign the full filename as
    // index, and the value will be the file extension
    foreach ($filenames as $key => $value) {
        $output[$value] = end(explode('.', $value));
    }

    // Return an array holding the file extensions
    return $output
    
}
Advertisements

Create a free website or blog at WordPress.com.