Home > Net >  Checking if individual variable is empty from an array PHP
Checking if individual variable is empty from an array PHP

Time:12-24

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  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  style="display:<?php echo $display; ?>">
   <p><?php echo $texta; ?></p>
</div>
<div  style="display:<?php echo $display; ?>">
   <p><?php echo $textb; ?></p>
</div>
<div  style="display:<?php echo $display; ?>">
   <p><?php echo $textc; ?></p>
</div>
....

CodePudding user response:

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  style="display:<?php echo $display[0]; ?>">
   <p><?php echo $texta; ?></p>
</div>
<div  style="display:<?php echo $display[1]; ?>">
   <p><?php echo $textb; ?></p>
</div>
<div  style="display:<?php echo $display[2]; ?>">
   <p><?php echo $textc; ?></p>
</div>

CodePudding user response:

Personally I will try for something like this :

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