0

I have a for each loop like this

      $sn_count = 1;
      $prodfilter = "";
      foreach($prods as $prod){
        $prodfilter .= "<div class=\"product\">".$prod['product'][1]."</div>";
        $sn_count++;
      }
      echo $prodfilter;

Now my problem my "product" class displaying border even if the $prod['product'][1] not available. So i would like to test it using if statement.

If (product value available) {
$prodfilter .= "<div class=\"product\">".$prod['product'][1]."</div>";
}   

I tried like this.

if(!empty($prod['product'][1])) {
$prodfilter .= "<div class=\"product\">".$prod['product'][1]."</div>";
 }

But its not working.

2
  • Wait, your loop iterates on $steps but you are testing and outputting $prod... ?? You'll get the same thing out for each loop iteration. Commented Mar 22, 2012 at 0:33
  • @Michael: I noticed that too, but I'm assuming he left out other code to shorten it. Commented Mar 22, 2012 at 0:34

3 Answers 3

1

you can try couple of things

try this for a start

if(strlen(trim($prod['product'][$sn_count]))>0) {
 $prodfilter .= "<div class=\"product\">".$prod['product'][$sn_count]."</div>";
  }

or

if(isset($prod['product'][$sn_count])) {
 $prodfilter .= "<div class=\"product\">".$prod['product'][$sn_count]."</div>";
  }
Sign up to request clarification or add additional context in comments.

2 Comments

It will give you warnings that the key does not exist if it doesn't exist.
thats right. Dirty trick is to prepend @ to $prod to suppress the warnings ;) which off course is not preferred by will work.
1

The right thing in my opinion would be to check how many rows returned. I'll assume you are using MySQL since you did not specify. Please ask for additional help if you are not using it.

http://www.php.net/manual/en/function.mysql-num-rows.php

if (mysql_num_rows($prods)!=0) {
    //Do your code
}

This should check if your query returned more than 0 rows (so it needs to be drawn). Does it fix it?

Comments

0

The right thing to do is to check if it's empty as you tried, but since it fails there obviously is some data there. You could do a var_dump and figure out what and why it is there which probably leads you to the source of the problem.

If by available you mean declared then isset is the right function to use by the way.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.