簡體   English   中英

檢查數組 PHP 中的單個變量是否為空

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

如何檢查數組中是否只有 1 個單獨的變量為空? 我需要一個元素來顯示或不顯示,這取決於變量中是否有內容。 問題是,如果我添加多個變量,它會隱藏/顯示所有元素,而不是單獨顯示。 任何幫助表示贊賞。

什么有效:

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

我想做什么:

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

像這樣的東西:

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>

我個人會嘗試這樣的事情:

<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