检查所有数组项是否为空 PHP

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5040811/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 16:36:49  来源:igfitidea点击:

Checking if all the array items are empty PHP

phparraysvalidation

提问by Matt

I'm adding an array of items from a form and if all of them are empty, I want to perform some validation and add to an error string. So I have:

我正在从表单中添加一组项目,如果它们都为空,我想执行一些验证并添加到错误字符串中。所以我有:

$array = array(
    'RequestID'       => $_POST["RequestID"],
    'ClientName'      => $_POST["ClientName"],
    'Username'        => $_POST["Username"],
    'RequestAssignee' => $_POST["RequestAssignee"],
    'Status'          => $_POST["Status"],
    'Priority'        => $_POST["Priority"]
);

And then if all of the array elements are empty perform:

然后如果所有数组元素都为空,则执行:

$error_str .= '<li>Please enter a value into at least one of the fields regarding the request you are searching for.</li>';

回答by xzyfer

You can just use the built in array_filter

你可以只使用内置的array_filter

If no callback is supplied, all entries of input equal to FALSE (see converting to boolean) will be removed.

如果未提供回调,则所有等于 FALSE 的输入条目(请参阅转换为布尔值)将被删除。

So can do this in one simple line.

所以可以在一个简单的行中做到这一点。

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>';
}

回答by Capsule

implode the array with an empty glue and check the size of the resulting string:

用空胶对数组进行内爆并检查结果字符串的大小:

<?php if (strlen(implode($array)) == 0) echo 'all values of $array are empty'; ?>

回答by mulquin

An older question but thought I'd pop in my solution as it hasn't been listed above.

一个较旧的问题,但我认为我会出现在我的解决方案中,因为它没有在上面列出。

function isArrayEmpty($array) {
    foreach($array as $key => $val) {
        if ($val !== '')
            return false;
    }
    return true;
}

回答by Your Common Sense

you don't really need it.
You're going to validate these fields separately and by finishing this process you can tell if array was empty (or contains invalid values, which is the same)

你真的不需要它。
您将分别验证这些字段,通过完成此过程,您可以判断数组是否为空(或包含无效值,这是相同的)

回答by Mehran Nasr

simplify use this way:

以这种方式简化使用:

$array = []; //target array
$is_empty = true; //flag

foreach ($array as $key => $value) {
    if ($value != '')
        $is_empty = false;
}
if ($is_empty)
    echo 'array is empty!';
else
    echo 'array is not empty!';

回答by qbert220

Your definition of $array is incorrect and has single quotes. It should read:

您对 $array 的定义不正确并且有单引号。它应该是:

$array = array( 'RequestID' =>  $_POST["RequestID"],
                'ClientName' => $_POST["ClientName"],
                'Username' => $_POST["Username"],
                'RequestAssignee' => $_POST["RequestAssignee"],
                'Status' => $_POST["Status"],
                'Priority' => $_POST["Priority"] );

回答by Cosworth66

I had the same question but wanted to check each element in the array separately to see which one was empty. This was harder than expected as you need to create the key values and the actual values in separate arrays to check and respond to the empty array element.

我有同样的问题,但想分别检查数组中的每个元素,看看哪个是空的。这比预期的要困难,因为您需要在单独的数组中创建键值和实际值来检查和响应空数组元素。

print_r($requestDecoded);
$arrayValues = array_values($requestDecoded);  //Create array of values
$arrayKeys = array_keys($requestDecoded);      //Create array of keys to count
$count = count($arrayKeys);
for($i = 0; $i < $count; $i++){  
    if ( empty ($arrayValues[$i] ) ) {         //Check which value is empty
        echo $arrayKeys[$i]. " can't be empty.\r\n";
    } 
}

Result:

结果:

Array
(
    [PONumber] => F12345
    [CompanyName] => Test
    [CompanyNum] => 222222
    [ProductName] => Test
    [Quantity] =>
    [Manufacturer] => Test
)

Quantity can't be empty.

数量不能为空。

回答by Val

NOT TESTED BUT u get the logic :)

未测试,但你明白逻辑:)

$error = 0;
foreach ($array as $k => $v){
    if (empty($v)) {
        $error++;
    }
}

if ($error == count($array)) {
    $error_str .= '<li>Please enter a value into at least one of the fields regarding the request you are searching for.</li>';
}

回答by RobertPitt

this is pretty simple:

这很简单:

foreach($array as $k => $v)
{
    if(empty($v))
    {
        unset($array[$k]);
    }
}
$show_error = count($array) == 0;

you would also have to change your encapsulation for your array values to double quotes.

您还必须将数组值的封装更改为双引号。