开发者

PHP - If null value

I have the following coding:

<div class="product-top-icons">
  <div class="energy-rating-1"><img src="http://www.justhome.co/skin/frontend/default/just2011/images/assets/<?php echo $_product->getAttributeText('energy_rating_one');?>.jpg"></div>
  <div class="energy-rating-2"><img src="http://www.justhome.co/skin/frontend/default/just2011/images/assets/<?php echo $_product->getAttribute开发者_运维知识库Text('energy_rating_two');?>.jpg"></div>
  <div class="energy-rating-3"><img src="http://www.justhome.co/skin/frontend/default/just2011/images/assets/<?php echo $_product->getAttributeText('energy_rating_three');?>.jpg"></div>
  <div class="guarantee-icon"><img src="http://www.justhome.co/skin/frontend/default/just2011/images/assets/<?php echo $_product->getAttributeText('warranty');?>.jpg"></div>
</div>

I would like to add an if statement in there basically to say the following:

If the value in the 'energy_rating_one' attribute is null then don't display the division energy-rating-1, if the 'energy_rating_two' attribute is null then don't display the div energy-rating-2 and so on...


something like this:

<?php if($_product->getAttributeText('energy_rating_one') !== null): ?>
<div class="energy-rating-1"><img src="http://www.justhome.co/skin/frontend/default/just2011/images/assets/<?php echo $_product->getAttributeText('energy_rating_one');?>.jpg"></div>
<?php endif; ?>

and that for all the others as well.


 <?php
   function echoIfExists($argument) {
      $val = $_product->getAttributeText($argument);
      if($val)
           /*your echo stmt*/
   }

echoIfExists('energy_rating_one');
 /** continue here*/

 ?>


Make it easy on yourself. Just change the css class rules from energy-rating-1 to energy-rating-one and echo the variable you already have i.e energy-rating-one


You have a function "int_to_words" to transform "int" value into a text value in this post: http://www.php.net/manual/en/function.strval.php#41988

After that, you just have to iterate into all values

for(i = 0; i < 100; i++) {
    $item = 'energy_rating_'.int_to_words($i);
    if($_product->getAttributeText($item) != null){
      echo "<div class=\"energy_rating_$i\"><img src=\"http://www.justhome.co/skin/frontend/default/just2011/images/assets/".$_product->getAttributeText($item).".jpg\"></div>";
    }
}


Look at short hand if statement:

http://www.scottklarr.com/topic/76/ternary-php-short-hand-ifelse-statement/

$total==1 ? "is 1 item" : 
      "are ".($total == 0 ? "no items" : "$total items"
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜