Best practices: Wrap foreach()'s within check for non-empty array (where needed)

Also:
* sometimes replaced count( ) > 0 with !== array() as it's faster
* added some unset()'s, more should be added
Small tweaks and remove trailing whitespace