Invalid argument supplied for foreach()

后端 未结 19 1400
花落未央
花落未央 2020-11-21 06:32

It often happens to me to handle data that can be either an array or a null variable and to feed some foreach with these data.

$values = get_val         


        
相关标签:
19条回答
  • 2020-11-21 06:39

    Try this:

    //Force array
    $dataArr = is_array($dataArr) ? $dataArr : array($dataArr);
    foreach ($dataArr as $val) {
      echo $val;
    }
    

    ;)

    0 讨论(0)
  • 2020-11-21 06:40

    Use is_array function, when you will pass array to foreach loop.

    if (is_array($your_variable)) {
      foreach ($your_variable as $item) {
       //your code
    }
    }
    
    0 讨论(0)
  • 2020-11-21 06:42

    I am not sure if this is the case but this problem seems to occur a number of times when migrating wordpress sites or migrating dynamic sites in general. If this is the case make sure the hosting you are migrating to uses the same PHP version your old site uses.

    If you are not migrating your site and this is just a problem that has come up try updating to PHP 5. This takes care of some of these problems. Might seem like a silly solution but did the trick for me.

    0 讨论(0)
  • 2020-11-21 06:42

    I'll use a combination of empty, isset and is_array as

    $array = ['dog', 'cat', 'lion'];
    
    if (!empty($array) && isset($array) && is_array($array) {
        //loop
        foreach ($array as $values) {
            echo $values; 
        }
    }
    
    0 讨论(0)
  • 2020-11-21 06:46

    Personally I find this to be the most clean - not sure if it's the most efficient, mind!

    if (is_array($values) || is_object($values))
    {
        foreach ($values as $value)
        {
            ...
        }
    }
    

    The reason for my preference is it doesn't allocate an empty array when you've got nothing to begin with anyway.

    0 讨论(0)
  • 2020-11-21 06:47

    If you're using php7 and you want to handle only undefined errors this is the cleanest IMHO

    $array = [1,2,3,4];
    foreach ( $array ?? [] as $item ) {
      echo $item;
    }
    
    0 讨论(0)
提交回复
热议问题