0

I'm new to PHP and I know this is an easy one but still can't find a solution.

I have an array that holds 4 different images and I want to echo the results so my HTML looks like this:

<img src="<?php echo $results['image1']?>" >
<img src="<?php echo $results['image2']?>" >
<img src="<?php echo $results['image3']?>" >
<img src="<?php echo $results['image4']?>" >

But what if for example image4 is null? - i don't want to echo the whole <img src> tag line

How can i do it? Thanks?

0

3 Answers 3

1

Here is your work around example.

<?php
if(!empty($results['image1'])) echo '<img src="'.$results['image1'].'">';
if(!empty($results['image2'])) echo '<img src="'.$results['image2'].'">';
if(!empty($results['image3'])) echo '<img src="'.$results['image3'].'">';
if(!empty($results['image4'])) echo '<img src="'.$results['image4'].'">';
?>

try this code may it helps you. here i have check first if result not empty.

Sign up to request clarification or add additional context in comments.

Comments

1
<?php if(isset($results['image1']) && !empty($results['image1'])){ ?><img src="<?php echo htmlspecialchars($results['image1']}; ?>" ><?php } ?>
<?php if(isset($results['image2']) && !empty($results['image2'])){ ?><img src="<?php echo htmlspecialchars($results['image2']}; ?>" ><?php } ?>
<?php if(isset($results['image3']) && !empty($results['image3'])){ ?><img src="<?php echo htmlspecialchars($results['image3']}; ?>" ><?php } ?>
<?php if(isset($results['image4']) && !empty($results['image4'])){ ?><img src="<?php echo htmlspecialchars($results['image4']}; ?>" ><?php } ?>

Comments

0
<?if(isset($results['image1']) && $results['image1'] != ""){?><img src="<?=$results['image1']?>" ><?}?>

With this you check it the image is set. Do that for each of your images and you should be fine.
The isset is not necessary, but some setups of php throw a warning without it. Thus it's better practice to use it.

If you don't want all the short-tags, do it like this:

if(isset($results['image1']) && $results['image1'] != ""){echo "<img src='{$results['image1']}' >"; }

That should be about the fanciest you can do. the "x{$variable}y" works like "x".$variable."y" but is easier to write/read, if you like it.

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.