Posts: 2,536
Location: Western Maryland
|
Of course that's true -- it's called the tertiary operator. It is most appropriate to use when choosing between achieving one or two values for the purposes of assignment or printing. It is less appropriate when the function is printing (or echoing) and one of the values is null or empty string. Such would have been the case here, so a traditional "if" statement is most appropriate here. But your way is equally effective. The original problem would have looked like this:
PHP Code:
echo empty( $shop_pic ) ? "" : $shop_pic;
While equally functional, it does unnecessarily print an empty string when $shop_pic is empty and is not as immediately readable as the traditional if. But it is a valid solution.
With that said, it would be considerably more elegant if you had a placeholder image indicating that an image was not available (itself an image of course) named, for example, notAvail.jpg. Then you could do something like this:
PHP Code:
$unavailImg = "images/notAvail.jpg";
echo empty( $shop_pic ) ? $unavailImg : $shop_pic;
Or better yet, put all that logic into a function and just call that:
PHP Code:
// Within code, I want to display an image if available, otherwise a standard "not available" image.
$shop_pic = "images/myCoolPic.jpg";
displayImg( $shop_pic );
// ...... OR
$shop_pic = null;
displayImg( $shop_pic ); // will display the alternate image
function displayImg( $img )
{
$unavailImg = "images/notAvail.jpg";
$img = empty($img) ? $unavailImg : $img;
print "<img src=\"$img\" />";
}
__________________
—Kyrnt
Last edited by Kyrnt; 03-15-2005 at 08:15 AM..
Reason: Clarification in code
|