2 回答

TA貢獻1993條經(jīng)驗 獲得超6個贊
問題是您在循環(huán)中的每次迭代中都回響“好”。
您可以創(chuàng)建一個變量來保存狀態(tài)并檢查它并在循環(huán)后回顯:
// 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應(yīng)盡可能避免使用(如果您的結(jié)構(gòu)合理,則總是如此)。
還有你在循環(huán)中使用global $field;while的問題。如果您打算使用在該方法中導入的 using ,則應(yīng)在. 如果您不打算使用它,請刪除.$fieldforeach$fieldglobal $field;foreachglobal $field;

TA貢獻1875條經(jīng)驗 獲得超5個贊
我更喜歡使用array_filter()僅獲取非空值并將其計數(shù)與原始$_POST計數(shù)進行比較
<?php
# pretend like this was what was posted
$posted = [
'foo' => 'bar',
'bar' => 'foo',
'treybake' => 'is awesome?'
];
# your GLOBALS
$required = ['foo', 'treybake'];
# compare the count of the array without any empty elements
# vs original post count
if (count(array_filter($posted, function($el){return (!empty($el));})) === count($posted)) {
echo 'good';
} else {
echo 'something bad';
}
- 2 回答
- 0 關(guān)注
- 121 瀏覽
添加回答
舉報