简体   繁体   English

如何检查数组在 PHP 中的未指定索引处是否有空值?

[英]How to check if an array has an empty value at an unspecified index in PHP?

How can I check if any of the arrays contains empty fields (they are both dynamic arrays so the empty value can be in any index in both of them)?如何检查任何 arrays 是否包含空字段(它们都是动态 arrays 所以空值可以在它们的任何索引中)?

Array1 ( [0] => dfsg [1] => dfasg [2] => d5g [3] => )
Array2 ( [0] => d54fgv [1] => [2] => df4g4 [3] => d645 )

It would be good to know at which index as well, otherwise, just to know if there is any empty fields.最好知道在哪个索引处,否则,只需知道是否有任何空字段。

There are many ways to achieve this.有很多方法可以实现这一目标。 One that springs to mind is checking if the count of a filtered version is lesser than the original array.想到的一个是检查过滤版本的计数是否小于原始数组。 You can even customize this to specify which sort of filter-values you are looking for by supplying a closure to array_filter() .您甚至可以通过向array_filter()提供闭包来自定义它以指定您正在寻找的过滤器值类型。

if (count(array_filter($a1)) < count($a1)) {
    echo '$a1 has at least one empty value';
}

From the manual of array_filter() ,array_filter()的手册中,

If no callback is supplied, all entries of array equal to FALSE (see converting to boolean ) will be removed.如果没有提供回调,所有等于 FALSE 的数组条目(请参阅转换为 boolean )将被删除。

If you need to know which index(es) is empty, you can check the difference of the filtered array with the original array through array_diff() .如果您需要知道哪个索引为空,可以通过array_diff()检查过滤后的数组与原始数组的差异。 You can then use array_keys() on the filtered array to obtain all the indexes.然后,您可以在过滤后的数组上使用array_keys()来获取所有索引。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM