In your second bit of code, you moved the $class = $row['class']; outside the foreach loop. That means it will initially be set to null (because $row['class'] is undefined before the loop), so $row['class'] <>$class will always be true. Move it back inside the loop and it should work as before.