add checks around $categories foreach