为什么我的代码返回多个回显字符串

每当我提交表单时,它都会将“Good”返回“GoodGoodGood”三倍,我正在尝试找出原因。我所知道的唯一一件事就是它必须对数组做一些事情。


check.php 检查所有 3 个输入是否都为空,如果一切正常,则回显“好”。


class Check {

    public function mty() {

        global $required;

        global $field;


        foreach($required as $field) {

            if (empty($_POST[$field])) {

                //Code...

            } else {

                echo "Good";

            }

        }

    }

}

submit.php


$check = new Check;


//Gets names of inputs

$required = array('name', 'price', 'id');


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

    $check->mty();

}

我是 OOP 的新手,只想找到解决问题的方法。这段代码有什么我可以改进的地方吗?


慕妹3146593
浏览 107回答 2
2回答

ibeautiful

问题是您在循环中的每次迭代中都回响“好”。您可以创建一个变量来保存状态并检查它并在循环后回显:// The variable that keeps the state$success = true;foreach($required as $field) {    if (empty($_POST[$field])) {        // Set the state as false        $success = false;    }}// If state is true, no value was empty and we echo 'Good'... once.if ($success) {    echo 'Good';}正如其他人所提到的,global应尽可能避免使用(如果您的结构合理,则总是如此)。还有你在循环中使用global $field;while的问题。如果您打算使用在该方法中导入的 using ,则应在. 如果您不打算使用它,请删除.$fieldforeach$fieldglobal $field;foreachglobal $field;

慕田峪4524236

我更喜欢使用array_filter()仅获取非空值并将其计数与原始$_POST计数进行比较<?php&nbsp; &nbsp; # pretend like this was what was posted&nbsp; &nbsp; $posted = [&nbsp; &nbsp; &nbsp; &nbsp; 'foo' => 'bar',&nbsp; &nbsp; &nbsp; &nbsp; 'bar' => 'foo',&nbsp; &nbsp; &nbsp; &nbsp; 'treybake' => 'is awesome?'&nbsp; &nbsp; ];&nbsp; &nbsp; # your GLOBALS&nbsp; &nbsp; $required = ['foo', 'treybake'];&nbsp; &nbsp; # compare the count of the array without any empty elements&nbsp;&nbsp; &nbsp; # vs original post count&nbsp; &nbsp; if (count(array_filter($posted, function($el){return (!empty($el));})) === count($posted)) {&nbsp; &nbsp; &nbsp; &nbsp; echo 'good';&nbsp; &nbsp; } else {&nbsp; &nbsp; &nbsp; &nbsp; echo 'something bad';&nbsp; &nbsp; }
打开App,查看更多内容
随时随地看视频慕课网APP