简体   繁体   English

检查数组 PHP 中的单个变量是否为空

[英]Checking if individual variable is empty from an array PHP

How do I check if only 1 individual variable of the array is empty?如何检查数组中是否只有 1 个单独的变量为空? 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:

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

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

HTML: HTML:

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

What I would like to work:我想做什么:

PHP: 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: 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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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