Add if-not-empty check before foreach to prevent PHP warning (#4427)