Vince P
Vince P

Reputation: 1791

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->getAttributeText('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...

Upvotes: 4

Views: 22361

Answers (5)

jeanmatthieud
jeanmatthieud

Reputation: 358

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>";
    }
}

Upvotes: 0

Cups
Cups

Reputation: 6896

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

Upvotes: 0

check123
check123

Reputation: 2009

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

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

 ?>

Upvotes: 0

izip
izip

Reputation: 2096

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"

Upvotes: -3

Christophe
Christophe

Reputation: 4828

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.

Upvotes: 4

Related Questions