Let's say you have a simple while loop like this:

$query = "select * from table1"
$result = mysql_query($query);
while ($row = mysql_fetch_array($result))
{
$item_class = $row['item_class'];
$item_code = $row['item_code'];
$description= $row['description];
$cat_code= $row['cat_code];
}

The cat code is a number, 1 to 6. As the while loop is run, I want to determine at the end of the loop which cat codes haven't been returned. (Please don't suggest another mysql query as the actual set-up is a little more complicated than this and I'm trying to solve this through php)

So I'm thinking if you set a value like $cat_code_string = 1,2,3,4,5,6

If one of those values is returned in a row, then that number is removed from the string. And then the next loop $cat_code_string would have one less number.

This is an area I am weak in, so if someone could suggest how I could code this, I'd really appreciate it.

Thanks!

    Rather than using a string you could push each cat code into an array, and then inspect it afterward to find out which have not been found.

    // All possible cat codes (perhaps this would come from another query)
    $all_cat_codes = array( 1, 2, 3, 4, 5, 6 );
    while( ... )
    {
      ...
      $cat_codes[] = $row['cat_code'];
    }
    // Assume there will be duplicates
    $cat_codes = array_unique( $cat_codes );
    // Finds values in $all_cat_codes not present in $cat_codes
    $missing_codes = array_diff( $all_cat_codes, $cat_codes );
    

    Thinking about it using array_unique is not even necessary.

      Write a Reply...