Jump to content

suppress foreach error warnings


ashutoash

Recommended Posts

I use PHP's PDO extensively for data grabbing and inserting. When I am selecting data, the return is a PHP PDO object which in itself contains select statements. So I use foreach to parse through the object and build a table. For cells which I have data it's fine but for cells which do not get any data meaning that have no entry in the db, php throws out a error PHP Warning:  Invalid argument supplied for foreach().

I tried using if(is_array) and also @ to suppress them but no luck :'( :'( :'(. Can anyone point me to the right direction for suppressing these errors/warnings!!

Link to comment
https://forums.phpfreaks.com/topic/247086-suppress-foreach-error-warnings/
Share on other sites

do you need a code snippet...here is some:

 

$getSite = "SELECT * FROM orderTable WHERE siteName = 'Atlanta' ORDER BY siteName";
$getSiteResults = $getData->db->getLocalQuery($getSite);
foreach($getSiteResults as $site)
{
                 $result = $site["placeName"];
        }

 

I am getting data...that's fine but at some instances it throws the warning PHP Warning:  Invalid argument supplied for foreach(). I read online that using @ will suppress these errors...but for me it does not.

Suppression is BAD! Avoid doing it at all costs.

 

Instead, look into proper checks

 

<?php 

$var = array(
'key1' => 'val1',
'key2' => 'val2',
'key3' => 'val3',
);

if( is_array($var) || is_object($var) )
foreach( $var as $key => $value ) {
	echo $key. '=>' .$value. '<br>';
}
else echo 'Can not loop<br>';

/////////////////////////////////////////////////

class obj {
public $prop1 = 'val1', $prop2 = 'val2', $prop3 = 'val3';
private $prop4 = 'wontbeshown';
}
$var = new obj();

if( is_array($var) || is_object($var) )
foreach( $var as $key => $value ) {
	echo $key. '=>' .$value. '<br>';
}
else echo 'Can not loop<br>';

/////////////////////////////////////////////////

$var = FALSE;

if( is_array($var) || is_object($var) )
foreach( $var as $key => $value ) {
	echo $key. '=>' .$value. '<br>';
}
else echo 'Can not loop<br>';

?>

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.