0

On my page where there is an image, I added the alt and title attributes, and these fields are sometimes empty, sometimes they are not.

Now I'm taking it out like this:

<?php foreach ($images as $image) { ?> <img src="<?= $image->getImageUrl() ?>" alt="<?= $image->image_alt ?>" title="<?= $image->image_title ?>"> <?php } ?> 

And I need to add a check here, when these fields are empty, then do not display the alt and title attributes on the page.

I try to do something like this, but they still show up:

<?php foreach ($images as $image) { ?> <img src="<?= $image->getImageUrl() ?>" <?php if (!empty($image->image_alt) { ?> alt="<?= $image->image_alt ?>" <?php } ?> <?php if (!empty($image->image_title) { ?> title="<?= $image->image_title ?>" <?php } ?>> <?php } ?> 

Also tried like this:

<?php foreach ($images as $image) { ?> <img src="<?= $image->getImageUrl() ?>" <?php if (!empty($image->image_alt) && !empty($image->image_title)) { ?> alt="<?= $image->image_alt ?>" title="<?= $image->image_title ?>"> <?php } ?> <?php } ?> 

2 Answers 2

1

you can do it that way

<?php foreach ($images as $image) { if(!empty($image->getImageUrl() && !empty($image->image_alt) && !empty($image->image_title)) { ?> ..... 

i dont really know what to check but to check if a variable is empty, then use the empty function

If the value can be null

if(null !== $image->getImageUrl() && ....) 
Sign up to request clarification or add additional context in comments.

4 Comments

When there are several pictures, it does not work, attributes are displayed with empty fields anyway
that means that the content of each image's properties is not empty. Maybe blank space are not considered as empty. have you dump the content of each image's properties to see what they look like ? have you try to test with null?
yes, I get NULL
have you tried isset() instead of empty() ?
1

Hopping in and out PHP is always quite messy. First sort the data out, only then output the html.

$myImages=[]; foreach ($images as $key=>$image) { $src = 'src="'.$image->getImageUrl().'"'; $alt = (empty($image->image_alt) ? '' : 'alt="'.$image->image_alt.'"' ); $title = (empty($image->image_title) ? '' : 'title="'.$image->image_alt.'"' ); $myImages[]="<img $src $alt $title>"; } echo implode('',$myImages); 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.