Mat*_*att 72 php arrays validation
我正在从表单添加一个项目数组,如果所有项目都是空的,我想执行一些验证并添加到错误字符串.所以我有:
$array = array(
'RequestID' => $_POST["RequestID"],
'ClientName' => $_POST["ClientName"],
'Username' => $_POST["Username"],
'RequestAssignee' => $_POST["RequestAssignee"],
'Status' => $_POST["Status"],
'Priority' => $_POST["Priority"]
);
Run Code Online (Sandbox Code Playgroud)
然后,如果所有数组元素都为空,则执行:
$error_str .= '<li>Please enter a value into at least one of the fields regarding the request you are searching for.</li>';
Run Code Online (Sandbox Code Playgroud)
xzy*_*fer 155
您可以使用内置的array_filter
如果没有提供回调,则将删除所有输入等于FALSE的条目(请参阅转换为布尔值).
所以可以在一个简单的行中做到这一点.
if(!array_filter($array)) {
echo '<li>Please enter a value into at least one of the fields regarding the request you are searching for.</li>';
}
Run Code Online (Sandbox Code Playgroud)
Cap*_*ule 17
使用空胶水内爆数组并检查结果字符串的大小:
<?php if (strlen(implode($array)) == 0) echo 'all values of $array are empty'; ?>
Run Code Online (Sandbox Code Playgroud)
一个较老的问题,但我认为我会在我的解决方案中弹出,因为它没有在上面列出.
function isArrayEmpty($array) {
foreach($array as $key => $val) {
if ($val !== '')
return false;
}
return true;
}
Run Code Online (Sandbox Code Playgroud)