Replacing query building loop with PHP's built-in method