Removing use of foreach where appropriate