dongyin8009 2015-11-09 15:27
浏览 21
已采纳

当包含它的函数依赖于$ _POST数据时,如何禁止此foreach警告

I have the following code which functions as intended when $_POST values are set, however, if no $_POST values(IE when the page is first loaded) are set I get "Warning: Invalid argument supplied for foreach() in..." $_POST is always going to be empty until the user clicks submit. I have tried empty(), isset() and now count().

if(isset($_POST['submitbtn'])){

$errors = CheckFormErrors();

    if(count($errors) == 0){
        $data = CleanFormData();
        print_r($data);
    }
}

Here is the function being called(not yet complete, but it is working):

function CleanFormData(){
    foreach($_POST as $key => $value){
        if($key == 'description'){ continue; }
        if($key == 'file'){ continue; }
        if($key == 'role'){ continue; }

        $_POST[$key] = is_array($key) ? $_POST[$key]: strip_tags($_POST[$key]);
    }
        return $_POST;
}

I thought that I could surpress the error by putting it in a conditional statement, evidently that is incorrect. A little help?

  • 写回答

1条回答 默认 最新

  • duanche5149 2015-11-09 15:37
    关注

    As already stated in comments, you have to check if the superglobal $_POST is empty before calling the foreach itself (inside the function), not outside the function - this way you don't have to check for !empty($_POST) every time you are calling this function.

    function CleanFormData() {
        if (!empty($_POST)) {
            foreach($_POST as $key => $value) {
                // Loops here
            }
        }
        return $_POST;
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 spss统计中二分类变量和有序变量的相关性分析可以用kendall相关分析吗?
  • ¥15 拟通过pc下指令到安卓系统,如果追求响应速度,尽可能无延迟,是不是用安卓模拟器会优于实体的安卓手机?如果是,可以快多少毫秒?
  • ¥20 神经网络Sequential name=sequential, built=False
  • ¥16 Qphython 用xlrd读取excel报错
  • ¥15 单片机学习顺序问题!!
  • ¥15 ikuai客户端多拨vpn,重启总是有个别重拨不上
  • ¥20 关于#anlogic#sdram#的问题,如何解决?(关键词-performance)
  • ¥15 相敏解调 matlab
  • ¥15 求lingo代码和思路
  • ¥15 公交车和无人机协同运输