Can't see the error with my code for "Warning: Invalid argument supplied for foreach()"

38 views Asked by At

I'd be grateful if anyone can cast an eye over this error with my php? It worked locally but when I published it live it generated this error:

******* UPDATE: If there is null data then the error is created so I need to create an ELSE statement right?

Warning: Invalid argument supplied for foreach() in [line #]

Thanks for all input and help!

                <?php
                $categories = get_the_category();
                foreach($categories as $cat):?>

                <a href="<?php echo get_category_link($cat->term_id);?>" class="badge badge-primary" style="margin-bottom:5px;"><?php echo $cat->name;?></a>

                <br>

                <?php endforeach;?>
                <?php
                $tags = get_the_tags();
                foreach($tags as $tag):?>

                  <a href="<?php echo get_tag_link($tag->term_id);?>" class="badge badge-light"><?php echo $tag->name;?></a>

                <?php endforeach;?>
1

There are 1 answers

1
bishop On

Either $categories or $tags is not an array, likely a null. If you expect this, you can - in modern versions of PHP - sidestep the issue:

foreach(($categories ?? []) as $cat):

or

foreach(($tags ?? []) as $tag):

Where:

  • ?? is the null-coalescing operator. It returns the left-hand side if it's non-empty, otherwise the right-hand side.
  • [] is short array syntax, and equivalent to array ()

So this says to use, for example, $tags if it's not-empty otherwise use an empty array. This handles most use cases, provided your getter methods return either an array or a null.

Note that the surrounding parentheses are optional; I prefer their readability. You could just as well do, for example, foreach($tags ?? [] as $tag):