I'm trying to implement this code I have, but the if else statement does not seem to be working. I want to use a default image if there is no image returned in the $photo array. $photo = $link->getGbaseAttribute("image_link"); foreach ($photo as $image) { if ($image->text){ echo $image->text; } else { echo "basic.jpg"; } } Code (markup):
Sometimes it does and sometimes it doesn't. That script is in a foreach loop. Some of the entries have text in the image and sometimes the data is missing. I wanted to write a loop that would check to see if it existed then printed the default image if it did not.
Try this $photo = $link->getGbaseAttribute("image_link"); foreach ($photo as $image) { if (strlen($image->text)>0){ echo $image->text; } else { echo "basic.jpg"; } } PHP: If you are never getting your basic.jpg, thats because $image->text is always returning true. Checking the actual String Length avoids confusion. Let me know if that does the trick for you. Cheers Tim
allow only gif and jpg, for example.. $photo = $link->getGbaseAttribute("image_link"); foreach ($photo as $image) { if (substr($image->text,-4) == ".gif" || substr($image->text,-4) == ".jpg"){ echo $image->text; }else { echo "basic.jpg"; } } PHP:
I assume the first line always returns an array even on error. If not, you would want to check it before throwing $photo into a foreach. $photo = $link->getGbaseAttribute("image_link"); foreach ($photo as $image) { if (!empty($image->text)){ echo $image->text; } else { echo "basic.jpg"; } } PHP:
always initiate a clean array if you are expecting one $photo = array(); $photo = $link->getGbaseAttribute("image_link"); foreach ($photo as $image) { if (!empty($image->text)){ echo $image->text; } else { echo "basic.jpg"; } } Code (markup): or you can do $photo = array(); $photo = $link->getGbaseAttribute("image_link"); if(count($photo)>0) { foreach ($photo as $image) { if (!empty($image->text)){ echo $image->text; } else { echo "basic.jpg"; } } } else { echo "basic.jpg"; } Code (markup):
I kinda figured it out. I used the code that Gordaen and lfhost posted. Instead of just printing the variable $image->text I had it print the whole image source. I couldn't get it to work by printing the basic.jpg with the if loop, but this works for my own purposes. Thanks guys.