Image Extension Wild Card

I could have sworn I knew how to do this, but I’m having trouble figuring it out even with the tutorials I’ve found. I simply want to display an image, where $MyURL = the page URL. Most of the images are jpg’s, but I want to replace “jpg” with a wildcard to allow images with other extensions.

This appears to be a common way of doing it, but I get an “array to string conversion” error.

$Extension =  array('gif', 'png', 'jpg');

$imageURL = '/images/states/'.$MyURL.'.'.$Extension.'';
if (getimagesize($imageURL) !== false) {
    echo '<img src="'.$imageURL.'';
}

Can anyone tell me what I’m doing wrong? Thanks.

Yes, you’re trying to append an array where a string is needed.
(like the error message indicates)

You need to do a loop of some sort or specify an array key so the value is a string.

I tried the array_search function, but it says it expects “two parameters” but was only give one.

$imageURL = 'http://gs/images/sections/world/top/'.$DesigGen.'/'.$ImgParent.'/'.$MyID2.'.'.array_search($Extension).'';

The array_search function needs a “needle” and a “haystack”, you gave it only the haystack.

The PHP documentation can be your friend

http://php.net/manual/en/function.array-search.php

I don’t understand their example…

$key = array_search('green', $array);

With my script, that would presumably translate…

$key = array_search('jpg', $Extension);

But I’m not searching for a specific extension; I want the image to display regardless of its extension.

Wasn’t all this already covered in your other topic?

Well, that discussion convinced me to try something other than the glob function. :wink:

One of the suggestions was that I just forget about multiple image extensions and use one common extension. But since I’ll have some images with transparent backgrounds, I’ll resort to Plan C: I can just make a PHP switch listing images that are exceptions to the .jpg rule.

Thanks.

$extensions =  array('gif', 'png', 'jpg');
foreach($extensions as $extension) {
  $file = '/images/states/'.$imgName.'.'.$extension;
  if(file_exists(WEB_ROOT.$file)) {
    echo '<img src="'.$file.'"';
    break;
  }
}

Where WEB_ROOT is the absolute file path to the public web root with no trailing slash.

Got it - thanks.

And for any viewers who are using MAMP on a Mac, this is what the finished product looks like for me:

$extensions =  array('gif', 'png', 'jpg');
$Root = '/Applications/MAMP/htdocs/gs';
foreach($extensions as $extension) {
  $file = '/images/sections/flowers.'.$extension;
  if(file_exists($Root.$file)) {
	echo '<img src="'.$file.'">';
    break;
  }
}
1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.