vine animals
vine animals

Reputation: 9

php code not working, what is wrong with the codes?

I am trying to fix some codes, but can't find it out. i hope you guys can help me!

errors:

Warning: Invalid argument supplied for foreach() in /home//public_html/wp-content/plugins//view/import.php on line 148

<?php foreach ($product['sku_products']['attributes'] as $attr): ?>

Warning: Invalid argument supplied for foreach() in /home//public_html/wp-content/plugins//view/import.php on line 209

<?php foreach ($product['sku_products']['variations'] as $i => $var):
 ?>

thank you a lot.

Upvotes: 0

Views: 44

Answers (1)

Akshay Hegde
Akshay Hegde

Reputation: 16997

foreach expects argument should be array or object

In your case $product['sku_products']['attributes'] could be either null or false or not array

So what you can do is as below using isset() and is_array()

if(isset($product['sku_products']['attributes']) && is_array($product['sku_products']['attributes']))
{
   foreach ($product['sku_products']['attributes'] as $attr):
}

Modify your view like below

<?php if(isset($product['sku_products']['attributes']) && is_array($product['sku_products']['attributes'])):?>
   <?php foreach ($product['sku_products']['attributes'] as $attr): ?>
          <p>Your contents goes here</p>
   <?php endforeach;?>
<?php endif;?>

Here is example for testing

$ php -r 'foreach(null as $test){}'
PHP Warning:  Invalid argument supplied for foreach() in Command line code on line 1

$ php -r 'foreach(false as $test){}'
PHP Warning:  Invalid argument supplied for foreach() in Command line code on line 1

$ php -r '$p="string";foreach($p as $test){}'
PHP Warning:  Invalid argument supplied for foreach() in Command line code on line 1

Upvotes: 2

Related Questions