检查一个数组是否有没有值的键,然后这样做(PHP)?
Check if an array has a key without a value, then do this (PHP)?
假设我有一个如下所示的数组:
Array
(
[0] =>
[1] => 2017-01-01 00:00:00
)
如何动态检查该区域是否有任何空值?
您可以使用 empty()
:
$array = [
null,
'2017-01-01 00:00:00',
'',
[],
# etc..
];
foreach($array as $key => $value){
if(empty($value)){
echo "$key is empty";
}
}
有关详细信息,请参阅 type comparison table。
类似
// $array = [ ... ];
$count = count($array);
for( $i=0; $i<=$count; $i++){
if( $array[$count] == 0 ){
// Do something
}
}
您可以通过将数组值与 array_filter
(删除空值)的结果进行比较来查看它是否有任何空值。
$has_empty_values = $array != array_filter($array);
为此你有更多的可能性:
不用第二个参数就可以使用array_filter
函数
array_filter([ 'empty' => null, 'test' => 'test']);
但是要小心,因为这会删除所有等于 false (null, false, 0)
的值
您可以使用 array_filter
带有回调函数的函数:
function filterEmptyValue( $value ) {
return ! empty( $value );
}
array_filter([ 'empty' => null, 'test' => 'test'], 'filterEmptyValue');
您可以使用 foreach 或 for:
$array = ['empty' => null, 'test' => 'test'];
foreach($array as $key => $value) {
if(empty($value)) {
unset($array[$key]);
}
}
$array = [null, 'test'];
for($i = 0; $i < count($array); $i++){
if(empty($array[$i])) {
unset($array[$i]);
}
}
这是示例,因此您必须思考并针对您的问题做出好的解决方案
假设我有一个如下所示的数组:
Array
(
[0] =>
[1] => 2017-01-01 00:00:00
)
如何动态检查该区域是否有任何空值?
您可以使用 empty()
:
$array = [
null,
'2017-01-01 00:00:00',
'',
[],
# etc..
];
foreach($array as $key => $value){
if(empty($value)){
echo "$key is empty";
}
}
有关详细信息,请参阅 type comparison table。
类似
// $array = [ ... ];
$count = count($array);
for( $i=0; $i<=$count; $i++){
if( $array[$count] == 0 ){
// Do something
}
}
您可以通过将数组值与 array_filter
(删除空值)的结果进行比较来查看它是否有任何空值。
$has_empty_values = $array != array_filter($array);
为此你有更多的可能性:
不用第二个参数就可以使用
array_filter
函数array_filter([ 'empty' => null, 'test' => 'test']);
但是要小心,因为这会删除所有等于 false (null, false, 0)
的值您可以使用
array_filter
带有回调函数的函数:function filterEmptyValue( $value ) { return ! empty( $value ); } array_filter([ 'empty' => null, 'test' => 'test'], 'filterEmptyValue');
您可以使用 foreach 或 for:
$array = ['empty' => null, 'test' => 'test']; foreach($array as $key => $value) { if(empty($value)) { unset($array[$key]); } } $array = [null, 'test']; for($i = 0; $i < count($array); $i++){ if(empty($array[$i])) { unset($array[$i]); } }
这是示例,因此您必须思考并针对您的问题做出好的解决方案