The error regarding $attachments is most likely caused by an uninitialized array. The best way to solve is to initialize to an empty array before using it in any way.
The idea is to initialise it at the beginning, so values may be added from the form (or wherever values come from) after initialisation.
That way is will still be an array (and countable) even if it is still empty at the end, with no values added.