PHP Invalid Argument supplied for foreach()?

Can someone please explain to me why I get the warning for an invalid argument for the following code?:

public function do_user_directory() {
$users = $this->load_all_user_objects();
				
foreach ( $users as $user ) { ?>
  <div class="directory_item">
     <h3><a href="profile-view.php?uid=<?php echo $user->id; ?>"><?php echo $user->user_nicename; ?></a></h3>
    <p><?php echo $user->user_email; ?></p>
  </div>
<?php
  }
}

Thanks to anyone who replies in advance :smile:

You’re getting the error because PHP is expecting the $users variable to be an array and it’s not finding an array. Add this line before the line where you fill up $users

$users=array();

That will set up $users as an array, so if it’s empty the foreach will get the array that it expects, even if that array is empty

I’ve added “$users = array();” before the public function like you said, and now I receive this error:

“Parse error: syntax error, unexpected ‘$users’ (T_VARIABLE), expecting function (T_FUNCTION) in C:\Program Files (x86)\Ampps\www\includes\class-query.php on line 107”

I’ve also tried putting it within the public function, but then I still receive the original error.

Does load_all_user_objects() always return an array, populated or otherwise?

I think I’ve figured. I’ll reply back to you if it doesn’t work out.

I think the $users=array(); should have been inside the function load_all_user_objects()

I endeavour to adopt the PHP approach and to return FALSE if the expected results are not satisfied. It is then easier to use the following script:

public function do_user_directory() {
$users = $this->load_all_user_objects(); // assuming FALSE is returned if no users

if( $users ) {				
   foreach ( $users as $user ) { ?>
      <div class="directory_item">
         <h3><a href="profile-view.php?uid=<?php echo $user->id; ?>"><?php echo $user->user_nicename; ?></a></h3>
        <p><?php echo $user->user_email; ?></p>
      </div>
   <?php } // endforeach 

}else{ 
   echo 'Opportunity to resume with a graceful error message';
}//endif $users

}// endfunc  do_user_directory() 


**# alternative which I find is more readable and easier for debugging:** ``` // maybe FALSE is NOT returned if no users // is_array( $users ) {

// FALSE is returned if no users
if( $users ) {
foreach ( $users as $user ) {
echo ‘

’;
echo ‘

’ .$user->user_nicename .‘>

’;
echo ‘

’ .$user->user_email .‘

’;
echo ‘
’;
} // endforeach

}else{
echo ‘Opportunity to resume with a graceful error message’;
}//endif $users

Try the following code -
if (is_array($values) || is_object($values))
{
foreach ($values as $value)
{

}
}

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.