So you should try to take everything that doesn't change out of the loop. Often you use a function to check the maximum of times it should loop. Like here:
www.php.net