Home > Software design >  Do not display attributes if the field is empty
Do not display attributes if the field is empty

Time:05-28

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 } ?>

CodePudding user response:

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() && ....)

CodePudding user response:

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); 
  • Related