【问题标题】:how to check empty or !empty field如何检查空或!空字段
【发布时间】:2015-08-03 19:03:15
【问题描述】:
<?php $j=0; 
      while ($j<2){ if(empty($recent['id'][$k])) break;?>
      <div class="col-md-5 col-xs-7" style="padding:0px;">
       <div class="img-sm">
         <?php if(!empty($recent['image'][$k])) { ?>
          <img class="img-responsive" src="<?php echo base_url().url_thumb($recent['image'][$k],'konsultasi/') ?>" />
         <?php } else { ?>
           <img class="img-responsive" src="<?php base_url().'assets/images/logo.png' ?>" />
         <?php } ?>
       </div>

    </div>
<?php $j++; $k++; } ?>

问题是,如果空图像对我不起作用。

【问题讨论】:

  • 你能发布你的$recent数组
  • 发布var_dump($recent)的输出。
  • 我会假设正在检查的内容!empty 不是数组,不存在。尝试使用 'isset()' 和 '!= NULL' 的组合
  • 这是它 array(4) { ["id"]=> array(2) { [0]=> string(1) "2" [1]=> string(1) " 1" } ["image"]=> array(2) { [0]=> string(69) "assets/images/uploads/konsultasi/010df4f05a905f167421ecda7fd1fdd0.jpg" [1]=> string(69) "assets/images /uploads/konsultasi/da573b42cfd55cb8df80500bb866bef5.jpg" } ["title"]=> array(2) { [0]=> string(9) "test lagi" [1]=> string(18) "testing konsultasi" } [ “日期”]=> 数组(2){ [0]=> 字符串(11)“2015 年 7 月 14 日”[1]=> 字符串(11)“2015 年 7 月 13 日”} }

标签: php if-statement


【解决方案1】:

来自empty function documentation

如果 var 存在并且具有非空、非零值,则返回 FALSE。否则返回 TRUE

以下内容被认为是空的:
• ""(空字符串)
• 0(0 为整数)
• 0.0(0 作为浮点数)
• “0”(0 作为字符串)
• 空
• 错误
• array()(一个空数组)
• $var; (声明的变量,但没有值)

只是您的$recent['image'][$k] 与上述empty() 返回FALSE 的情况不匹配。

也许你的字符串里面有空格字符。尝试使用:

if (empty(trim($recent['image'][$k])))

【讨论】:

    【解决方案2】:

    你没有在 while 循环之前声明你的 k 变量。

    添加:$k = 0;

    我会这样做:

    <?php
    
    //Init loop var
    $i = 0;
    
    //Loop over results
    while($i < 2){
    
       //Skip loop if no id found
       if(empty($recent['id'][$i]) continue;
    
       //Output containers
       echo '<div class="col-md-5 col-xs-7" style="padding:0px;">';
       echo '<div class="img-sm">';
    
       //Check has image, output dependent
       if(!empty($recent['image'][$i])){
           echo '<img class="img-responsive" src="<?php echo base_url().url_thumb($recent['image'][$i],'konsultasi/') ?>" />';
       }
       else{
           echo '<img class="img-responsive" src="<?php base_url().'assets/images/logo.png' ?>" />';
       }
    
       //Close containers
       echo '</div></div>';
    
       //Increment counter
       $i++;
    
    }
    
    ?>
    

    编辑:也许保留你的输出方式,使用浏览器而不是 php(在这个编辑器中太懒了)。但请注意,我只使用一个计数器变量来尝试避免混淆。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-09-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-09-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多