Invalid argument supplied for foreach()

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

    
        ...
    
    

提交回复
热议问题