Mostafa AHmadi Mostafa AHmadi - 1 month ago 7
PHP Question

Invalid argument supplied for foreach Error

It happens a lot to me to handle data that can be either an array or a null variable and to feed some

foreach
with these data.

// TV shows categories
$tvcats = get_the_terms($post->ID, 'tvshows_cat');
foreach($tvcats as $tvcat) $tvcats_arr[] = $tvcat->name;
if (count($tvcats_arr) > 1) $tvcats_str = $tvcats_arr[0] . '<br />' . $tvcats_arr[1]; // return first 2 terms
elseif (count($tvcats_arr) == 1) $tvcats_str = $tvcats_arr[0]; // return one term
else $tvcats_str = '';


and


if (!empty($tvcats_str)){
echo $tvcats_str;
}


tvshows_cat
is a custom taxonomy and it works like Category, (I mean it is second category list).

In this code I wanted to limit terms to 2. And it worked but I got an Error.

So how can I solve this?

Answer

You can try something like this:

$tvcats = get_the_terms($post->ID, 'tvshows_cat');
if (isset($tvcats) && !is_wp_error($tvcats)) {
    foreach($tvcats as $tvcat) {
       $tvcats_arr[] = $tvcat->name;
       if (count($tvcats_arr) > 1) $tvcats_str = $tvcats_arr[0] . '<br />' . $tvcats_arr[1]; // return first 2 terms
       elseif (count($tvcats_arr) == 1) 
           $tvcats_str = $tvcats_arr[0]; // return one term
       else 
           $tvcats_str = '';
    }
}
Comments