What is the most efficient way to determine the extension of a saved file, given that I know the name only and not the extension?
Valid types/extensions are .jpg, .png and .gif
For example, every item has an image, so the image name will be
item1.jpg or item1.png or item1.gif
item2.jpg or item2.png or item2.gif
etc.
The only way I can think of so far is looping through the three possibilities with
if(file_exists('item1.jpg')) {...
} elseif(file_exists('item1.png')) {...
} elseif(file_exists('item1.gif')) {...
}
Is there a more efficient way?
For efficient in terms of less code, you could do
$name = 'item23';
$images = glob("images/$name.???");
$image = $images ? $images[0] : '';
which should return the first file matching your filename, regardless of which extension it has, or ''
if no matching file is found. I think that should also be more efficient in terms of execution time than checking file_exists
three times.
In my unsolicited opinion, I think storing the full paths to images associated with your articles isn't a bad idea.