2 回答
TA贡献1993条经验 获得超5个赞
问题是您在循环中的每次迭代中都回响“好”。
您可以创建一个变量来保存状态并检查它并在循环后回显:
// 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;
TA贡献1875条经验 获得超5个赞
我更喜欢使用array_filter()仅获取非空值并将其计数与原始$_POST计数进行比较
<?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 关注
- 106 浏览
添加回答
举报