简体   繁体   中英

Checking if individual variable is empty from an array PHP

How do I check if only 1 individual variable of the array is empty? I would need an element to display or not, depending on if there is content in the variable. Problem is, if I add more than one variable, it hides/shows the element for all, instead of individually. Any help appreciated.

What works:

PHP:

<?php
$texta = CFS()->get( 'sometexta' );

if ($texta !='') {
  $display = 'block';
} else {
  $display = 'none';
}
?>

HTML:

<div class="element" style="display:<?php echo $display; ?>">
   <p><?php echo $texta; ?></p>
</div>
....

What I would like to work:

PHP:

<?php
$texta = CFS()->get( 'sometexta' );
$textb = CFS()->get( 'sometextb' );
$textc = CFS()->get( 'sometextc' );

$alltext = array($texta, $textb, $textc);

foreach ( $alltext as $text) {
  if ($text !='') {
    $display = 'block';
  } else {
    $display = 'none';
  }
}
?>

HTML:

<div class="element" style="display:<?php echo $display; ?>">
   <p><?php echo $texta; ?></p>
</div>
<div class="element" style="display:<?php echo $display; ?>">
   <p><?php echo $textb; ?></p>
</div>
<div class="element" style="display:<?php echo $display; ?>">
   <p><?php echo $textc; ?></p>
</div>
....

Something like this:

PHP

<?php
  $texta = CFS()->get( 'sometexta' );
  $textb = CFS()->get( 'sometextb' );
  $textc = CFS()->get( 'sometextc' );

  $alltext = array($texta, $textb, $textc);

  $display = [];
  foreach($alltext as $text){
    if ($text !='') {
      $display[] = 'block';
    } else {
      $display[] = 'none';
    }
  }
?>

HTML

<div class="element" style="display:<?php echo $display[0]; ?>">
   <p><?php echo $texta; ?></p>
</div>
<div class="element" style="display:<?php echo $display[1]; ?>">
   <p><?php echo $textb; ?></p>
</div>
<div class="element" style="display:<?php echo $display[2]; ?>">
   <p><?php echo $textc; ?></p>
</div>

Personally I will try for something like this:

<div class="element" style="display:<?php ($texta!="") ? echo "block" : echo "none"; ?>">
   <p><?php echo $texta; ?></p>
</div>
<div class="element" style="display:<?php ($textb!="") ? echo "block" : echo "none"; ?>">
   <p><?php echo $textb; ?></p>
</div>
<div class="element" style="display:<?php ($textc!="") ? echo "block" : echo "none"; ?>">
   <p><?php echo $textc; ?></p>
</div>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM