Check if array is null before foreach to avoid NullPointerException