I have the following FOREACH comparing a session variable to a database string delimited with ",". Assuming that string is "1,2" and $_SESSION['id']="1", it should break the loop and forget the ELSE - shouldn't it??

foreach (explode(",",$row2['review_subscribers']) as $subscriber) {
 if ($subscriber==$_SESSION['id']) { 
  echo '<input type="checkbox" name="subscription" value="unsubscribe" />&nbsp;Unsubscribe from this topic';
  break;
 } else { 
  echo '<input type="checkbox" name="subscription" value="subscribe" />&nbsp;Subscribe to this topic';
 }
}

For some reason when the condition in the IF statement is met, it style echoes the ELSE and doesn't break out of the FOREACH.

Any ideas?

Thanks in advance.

    sleepydad wrote:

    I have the following FOREACH comparing a session variable to a database string delimited with ",". Assuming that string is "1,2" and $_SESSION['id']="1", it should break the loop and forget the ELSE - shouldn't it??

    Yes. Here is an example script:

    <?php
    
    $input = "1,2";
    $id = "1";
    
    foreach (explode(",", $input) as $subscriber) {
        if ($subscriber == $id) { 
            echo '<input type="checkbox" name="subscription" value="unsubscribe" />&nbsp;Unsubscribe from this topic';
            break;
        } else { 
            echo '<input type="checkbox" name="subscription" value="subscribe" />&nbsp;Subscribe to this topic';
        }
    }

    Running this script, I got the output of a checkbox and "Unsubscribe from this topic". In other words, the problem is more likely to lie with your input than with the code logic, e.g., $_SESSION['id'] does not contain "1" or "2".

    By the way, this is a poor approach to begin with. Your database field should not be a multi-valued field. Instead of storing values like "1,2", you should be normalising your database to have different rows.

      laserlight;11053825 wrote:

      Running this script, I got the output of a checkbox and "Unsubscribe from this topic". In other words, the problem is more likely to lie with your input than with the code logic, e.g., $_SESSION['id'] does not contain "1" or "2".

      By the way, this is a poor approach to begin with. Your database field should not be a multi-valued field. Instead of storing values like "1,2", you should be normalising your database to have different rows.

      Hear, Hear.

      Quick debug:

      foreach (explode(",",$row2['review_subscribers']) as $subscriber) {
      
       echo "<h3>Checking subscriber $subscriber</h3>\n";  //alternate, enclose in HTML comment brackets
      
       if ($subscriber==$_SESSION['id']) { 
        echo '<input type="checkbox" name="subscription" value="unsubscribe" />&nbsp;Unsubscribe from this topic';
        break;
       } else { 
        echo '<input type="checkbox" name="subscription" value="subscribe" />&nbsp;Subscribe to this topic';
       }
      }
        Write a Reply...