我正在尝试创建代码以检查数组是否在有效值之间或之前有空值。
起初,我尝试使用array_filter删除空值,然后检查有效值的其余索引是否是连续的,但我认为可能有一种简单的方法。
以下是示例
这些数组被视为VALID
Array =>
0 => string '030208000000000'
1 => string ''
2 => string ''
Array =>
0 => string '030208000000000'
1 => string '030210700000000'
2 => string ''
这些数组被视为无效
Array =>
0 => string '030208000000000'
1 => string ''
2 => string '030210500000000'
Array =>
0 => string ''
1 => string '030208000000000'
2 => string '030210500000000'
答案 0 :(得分:1)
您可以使用带有标志的旧循环,以检查是否已清空。
function IsArrayValid($MyArray)
{
$EmptyFound = false;
$NonEmptyFound = false;
foreach ($MyArray as $value)
{
if ($value !== '') // we found something non empty
{
$NonEmptyFound = true;
if ($EmptyFound) // we already found something empty before.
{
// array is invalid
// we can leave the loop and the function now
return false;
}
}
else // we found something empty
{
$EmptyFound = true;
}
}
// looks like we didn't find anything invalid
// return the value of $NonEmptyFound to make sure that an array with only empty value
// will be invalid
return $NonEmptyFound;
}
$ValidArray1 = array('foo', '', '');
$ValidArray2 = array('foo', 'bar', '');
$InvalidArray3 = array('foo', '', 'bar');
$InvalidArray4 = array('', '', 'foo');
echo "array 1 is valid ? " . (IsArrayValid($ValidArray1) ? "yes" : "no") . PHP_EOL;
echo "array 2 is valid ? " . (IsArrayValid($ValidArray2) ? "yes" : "no") . PHP_EOL;
echo "array 3 is valid ? " . (IsArrayValid($InvalidArray3) ? "yes" : "no") . PHP_EOL;
echo "array 4 is valid ? " . (IsArrayValid($InvalidArray4) ? "yes" : "no") . PHP_EOL;
输出:
array 1 is valid ? yes
array 2 is valid ? yes
array 3 is valid ? no
array 4 is valid ? no
答案 1 :(得分:1)
从您给出的示例来看,似乎唯一有效的列表是数组从头开始具有值且在末尾只有空值的列表。
假设是这样,它使用array_filter()
删除空项目,然后将剩余的键与简单的range()
从0到剩余元素-1的数量进行比较...
$a = [ '030208000000000', '', '' ];
// $a = [ '030208000000000', '030210700000000', '' ];
// $a = [ '', '030208000000000', '030210500000000' ];
// $a = [ '030208000000000', '', '030210500000000' ];
$b = array_filter($a);
if ( array_keys($b) == range(0, count($b)-1)) {
echo "valid";
}
else {
echo "invalid";
}
如果您需要确保将'0'视为有效,则可以将过滤器更改为
$b = array_filter($a, function ($val) { return $val !== ''; });
答案 2 :(得分:1)
当您对数组进行过滤以摆脱空值时,您可以将结果数组与该数组进行比较,并使用array_values
重新索引其所有键。
所以您的支票将是:
$filteredArray = array_filter($originalArray);
if ($filteredArray === array_values($filteredArray)) {
// all consecutive values / valid input
}