简体   繁体   中英

PHP Warning: Invalid argument supplied for foreach() error

I haven't been able to find a solution in the suggested questions that would help me solve this issue.

I have the following code, which does work, but it throws a PHP Warning: Invalid argument supplied for foreach() error.

In my code, I am adding any authors from $author2 to the $authdisplay array that have the same role as the primary author ($auth_role[0]).

I have checked to make sure that the $author2, $auth2_role, $auth_role, and $authdisplay are all arrays, and $author2 and $auth2_role have the same number of elements. ($author is a string.)

Any tips and help figuring this out would be appreciated.

   $author = $this->getPrimaryAuthor();
   $author2 = $this->getAuthor2Names();
   $auth_role = $this->getPrimaryAuthorsRoles();
   $auth2_role = $this->getAuthor2Roles();
   $authdisplay[] = $author;

  foreach($author2 as $key=>$field) {
       if ($auth2_role[$key] == $auth_role[0]) {
          $authdisplay[] = $field;
       }
   }
   return $authdisplay;
 }

Does it matter if $author2 is empty?

Typically you do this:

if (is_array($author2) && !empty($author2)) {
    foreach($author2 as $key=>$field) {
    #.... blah blah

    if (is_array($authdisplay) && !empty($authdisplay)) {
        return $authdisplay;
    }
    return false;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM