如何检查数组中的所有键在 PHP 中是否都有空值?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6339704/
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
How do i check if all keys in an array have empty values in PHP?
提问by Ibrahim Azhar Armar
I have an array
我有一个数组
$array = array('key1' => null, 'key2' => null, 'key3' => null, 'key4' => null);
i would like to determine if all the array keys have empty values if so then return false. the above example should return false as it does not have any value. but if one or more keys have any values then it should return true for example the below example is true.
我想确定所有数组键是否都有空值,如果是,则返回 false。上面的示例应该返回 false,因为它没有任何值。但是如果一个或多个键有任何值,那么它应该返回真,例如下面的例子是真。
$array = array('key1', 'key2' => value2, 'key3', 'key4' => value4);
回答by deceze
Assuming you actually mean an array like
假设你实际上是指一个数组
array('key1' => null, 'key2' => null, 'key3' => null, 'key4' => null)
the answer is simply
答案很简单
if (!array_filter($array)) {
// all values are empty (where "empty" means == false)
}
回答by Blagovest Buyukliev
Your assumption is incorrect. array('key1', 'key2', 'key3', 'key4')
has 4 values and keys in the range 0..3
.
你的假设是不正确的。array('key1', 'key2', 'key3', 'key4')
范围内有 4 个值和键0..3
。
array('key1', 'key2' => value2, 'key3', 'key4' => value4)
has the value key1
(with key 0), the key key2
, the value key3
(with key 1) and the key key4
.
array('key1', 'key2' => value2, 'key3', 'key4' => value4)
具有值key1
(键为 0)、键key2
、值key3
(键为 1)和键key4
。
回答by Ben Roux
@Blagovest is correct about your incorrect question presentation.
@Blagovest 关于您不正确的问题陈述是正确的。
$allEmpty = true;
foreach( $array as $key => $val ) {
if( isset( $array[$key] ) ) {
$allEmpty = false;
break;
}
}
// Do what you will with $allEmpty
回答by Paolo Stefan
I think what you mean is to check whether all keys are numeric or if at least one is string:
我认为您的意思是检查所有键是否都是数字或至少一个是字符串:
$ok = false;
foreach( array_keys($array) as $key ){
if(is_string($key)){
$ok=true;
break;
}
}
return $ok;
回答by Anonymous
$flag = 0;
foreach($array as $keys)
{
if(!isempty($keys)) {
$flag++;
}
}
if(flag > 0)
{
echo "Array not empty!";
}
else {
echo "Array empty!";
}
Should work.
应该管用。
回答by UWU_SANDUN
$array = array('key1' => null, 'key2' => null, 'key3' => null, 'key4' => null);
The answer is
答案是
$filterArray = array_filter($array);
if(count($filterArray) == 0){
return false;
}else{
return true;
}
回答by shlomicohen
Simple
简单的
count(array_filter($array)) != count($array)
If multidimensional
如果多维
count(array_filter(array_values($array))) != count(array_values($array))