Accessing Post ID Within Loop

The problem probably comes from whenever a $post has no terms set. You need to set $brand = array() outside your IF statement, add it just under get_the_terms(). At that point it also wouldn’t hurt to wrap your switch statement in a if( ! empty( $brand ) ) {

Another problem I see with this code is that you’re adding your term IDs to an array, then converting that array to a string, then switching them on an integer. So if you have a post assigned to Term 3 and Term 5, whenever it hits your join it will convert to string: '3, 5' and test the entire string against each case:

'3, 5' == 3 -> False

'3, 5' == 5 -> False

etc. You may just want to get the First term and test on that.

error code: 523