Invalid argument supplied for foreach()

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

提交回复
热议问题