views:

341

answers:

2

I have an array which contains the categories for a particular article ($link_cat). I'm then using mysql_fetch_array to print out all of the categories available into a list with checkboxes. While it's doing this I want it to compare the value it's on, to a value from the other array. If there is a match, then it means that one of the categories applies to this article, and it should print out a line of code to apply the checked attribute. great! except it's not working =[

    while ( $row = mysqli_fetch_array($results, MYSQLI_ASSOC) ){
 $cat[$i] = $row['category'];
 $cat_id[$i] = $row['cat_id'];

 echo '<li><input type="checkbox" ';

 $catCount = count($link_cat);
 for ($ct = 0; $ct < $catCount; $ct++){
  if ($cat_id[$i] == $link_cat[$ct]){ 
   echo 'checked="checked" ';
  }
 }

 echo 'name="' . $cat_id[$i] . '" />' . $cat[$i] . '</li>';

 $i++;
}

I've never really done a nested loop before (I suspect thats the problem).

The problem seems to be that when this runs, $link_cat[0] which will have the first category to check against in it - doesn't register. It comes up blank. Printing out variables inside the for loop confirmed this. Any others [1] [2] etc, are fine. It's just [0]. But why? it doesn't seem to make any sense. I know there is something in there, because I printed the contents of array as I filled it it, just to check. Yet it doesn't just show during the loop. Any ideas?

A: 

While I was originally very wrong about the array looping needing a reset, I can't shake the feeling that looping through that array isn't the fastest way to do what you are after.

Perhaps array_search would do, or maybe array_key_exists. in_array look like a winner but I didn't think of it

MrChrister
He's accessing by index, reset() is unnecessary.
Chad Birch
I get it. I will remove the dumb part of my response.
MrChrister
+10  A: 

slight bug fix (and blatant style change): Your version can print out checked="checked" multiple times. Do $cat and $cat_id need to be arrays?

while ( $row = mysqli_fetch_array($results, MYSQLI_ASSOC) ) {
    $cat = $row['category'];
    $cat_id = $row['cat_id'];

    echo '<li><input type="checkbox" ';
    if ( in_array($cat_id, $link_cat) ) {
        echo 'checked="checked" ';
    }
    echo "name='$cat_id' />$cat</li>";
}

For situation where one would normally throw a debugger at a problem, I like to throw in a nice print_r in a comment block (view-source for debug output, safer on live-ish sites).

echo '<!-- ' . print_r($link_cat, TRUE) . ' -->';
Ryan Graham
Thanks friend, much appreciated. Your way was much better, I'm learning :)
Jon