0

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;?>
Henry
  • 5,195
  • 7
  • 21
  • 34
  • 1
    `var_dump($categories);` and `var_dump($tags);`. The error pops up when the argument is invalid (not an array or object). Most likely either one of them (or both) is returning null. – icecub Jan 07 '20 at 03:38
  • Yes indeed - I discovered that if it is NULL then the error comes about...so need an "ELSE" statement... – Henry Jan 07 '20 at 03:39
  • Just wrap it inside `if (is_array($categories) || is_object($categories)) { ... } else { // do something else here }` – icecub Jan 07 '20 at 03:41
  • PHP 7? If is `if(is_iterable($categories)) { foreach ....` https://www.php.net/manual/en/function.is-iterable.php – user3783243 Jan 07 '20 at 03:42
  • Is this wordpress related? Seems like some sort of framework. Relevant maybe? – Funk Forty Niner Jan 07 '20 at 03:51

1 Answers1

0

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):

bishop
  • 37,830
  • 11
  • 104
  • 139