1
    <img src="socimages/logo/"<?php if ($soca == ""){ echo "logo.jpg"; } else { echo $anotherimage . ".jpg";} ?>>

Basically what I am trying to do is to change the end part of the image src, to pick from a range of specifically named images.

The syntax for the code is obviously not right since I closed the src after /logo/ with the ". But if I do not have the " then my php will not function.

3 Answers 3

2

I would suggest, don't mess the logic in your img tag.

<?php
    $img = ($soca == "") ? "logo.jpg" : $anotherimage.".jpg";
?>

<img src="socimages/logo/<?php echo $img; ?>" />
Sign up to request clarification or add additional context in comments.

Comments

0

Use a ternary, and remember to distinct between "" and '' :

<img src="socimages/logo/<? echo $soca == '' ? 'logo.jpg' : $anotherimage . '.jpg'; ?>">

This will produce a correct <img src="image.jpg"> tag.

Comments

0

A ternary conditional makes the line shorter:

<img src="socimages/logo/<?php echo ($soca=='')?'logo.jpg':$anotherimage.'.jpg';?>">

This is probably shortest:

<img src="socimages/logo/<?php echo ($soca=='')?'logo':$anotherimage;?>.jpg">

Or even this variant, but it depends on the short tags configuration of your site:

<img src="socimages/logo/<?= ($soca=='')?'logo':$anotherimage;?>.jpg">

But all variants are horrible style. You should always try to implement in a transparent manner, easy to read and understand. So instead store the final path inside a variable and echo that into the src attribute of the img tag.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.