An error from foreach is usually because what you're giving it isn't an array, and I can see a couple places in the code where if conditions aren't met, nothing gets added to the array so it will end up not being defined at all. So you could make sure they are defined as empty array, like for instance:
Code:
// Find OLD member group IDs (Removed Member Groups)
$addedmembergroupids = array();
foreach (explode(',', $userinfo['membergroupids']) AS $oldmembergroupid)
{