1

PHP Warning: Invalid argument supplied for foreach() in /home/synergie/public_html/ss/libraries/joomla/database/database/mysql.php on line 377

It comes up intermittently but often in both front and back of my joomla website. I am not expert in this area but it appears to be out of scope for everyone I ask for help. Since I cannot stop the error from occurring I was hoping you could help me to disable or block it from reporting.

this is the code I am dealing with:

  // If we want the whole field data object add that to the list.
            //else
            {
                foreach ($fields as $field)
                {
                    $result[$field->Field] = $field;
                }
            }

            return $result;
titus1972
  • 21
  • 1
  • 3

6 Answers6

4

Are you sure that you're looping through an array and not an object? Just to be sure, consider changing to:

foreach((array)$fields as $field)
{
    $result[$field->Field] = $field;
}
maiorano84
  • 11,574
  • 3
  • 35
  • 48
2

Maybe a try catch block?

try {
    foreach( $array as $v ) {
        // do dtuff
    }
} catch( Exception $e ) {
    echo 'Caught exception';
}
gimg1
  • 1,121
  • 10
  • 24
  • 1
    try / catch does not work for those kind of warnings unless you convert them into exceptions which is easily possible with [`ErrorException`](http://php.net/ErrorException). – hakre Apr 22 '12 at 09:19
2

You can turn off error reporting with this function:

error_reporting(0);
Hüseyin Z.
  • 836
  • 1
  • 8
  • 18
2

If this is a production environment and you simply want to disable warning messages like this (I'm assuming that this is code that you didn't write since you mention Joomla), try disabling error reporting in your php.ini file.

Change:

display_errors On

to

display_errors Off

Note that if this is a development environment you should probably leave error reporting on and fix any warnings.

bricriu
  • 210
  • 1
  • 3
2

Instead of hiding the error, you should be checking that you are passing something Traversable to foreach(). You can do that with @NullUserException's is_iterable():

function is_iterable($var) {
    return (is_array($var) || $var instanceof Traversable);
}

if(is_iterable($fields)) {
     foreach($fields as $field) {
         // Processing $field here
     }
} else {
    echo "Fields is not iterable";
}
Community
  • 1
  • 1
Bailey Parker
  • 15,599
  • 5
  • 53
  • 91
  • is_array() is probably the most simple way to check, but this is certainly more exhaustive – Ross Jan 18 '13 at 14:39
0

I would definitely choose the syntax:

if(is_array($fields)){
    foreach($fields as $field){
        //do stuff
    }
}

Be careful by using the nice and attractive short form :

foreach((array)$fields as $field)

if $fields contains complex data structure (not a simple array) the casting may compromise your content.

koalaok
  • 5,075
  • 11
  • 47
  • 91