Invalid argument supplied for foreach()

后端 未结 19 1334
花落未央
花落未央 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:32

    I usually use a construct similar to this:

    /**
     * Determine if a variable is iterable. i.e. can be used to loop over.
     *
     * @return bool
     */
    function is_iterable($var)
    {
        return $var !== null 
            && (is_array($var) 
                || $var instanceof Traversable 
                || $var instanceof Iterator 
                || $var instanceof IteratorAggregate
                );
    }
    
    $values = get_values();
    
    if (is_iterable($values))
    {
        foreach ($values as $value)
        {
            // do stuff...
        }
    }
    

    Note that this particular version is not tested, its typed directly into SO from memory.

    Edit: added Traversable check

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

    There seems also to be a relation to the environment:

    I had that "invalid argument supplied foreach()" error only in the dev environment, but not in prod (I am working on the server, not localhost).

    Despite the error a var_dump indicated that the array was well there (in both cases app and dev).

    The if (is_array($array)) around the foreach ($array as $subarray) solved the problem.

    Sorry, that I cannot explain the cause, but as it took me a while to figure a solution I thought of better sharing this as an observation.

    0 讨论(0)
  • 2020-11-21 06:35
    $values = get_values();
    
    foreach ((array) $values as $value){
      ...
    }
    

    Problem is always null and Casting is in fact the cleaning solution.

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

    First of all, every variable must be initialized. Always.
    Casting is not an option.
    if get_values(); can return different type variable, this value must be checked, of course.

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

    More concise extension of @Kris's code

    function secure_iterable($var)
    {
        return is_iterable($var) ? $var : array();
    }
    
    foreach (secure_iterable($values) as $value)
    {
         //do stuff...
    }
    

    especially for using inside template code

    <?php foreach (secure_iterable($values) as $value): ?>
        ...
    <?php endforeach; ?>
    
    0 讨论(0)
  • 2020-11-21 06:38

    Warning invalid argument supplied for foreach() display tweets. go to /wp-content/plugins/display-tweets-php. Then insert this code on line number 591, It will run perfectly.

    if (is_array($tweets)) {
        foreach ($tweets as $tweet) 
        {
            ...
        }
    }
    
    0 讨论(0)
提交回复
热议问题