我有以下数组:
if ( empty($a)||empty($b)||empty($c)){
if(empty($a)){
$errors[]="a is empty";
}
if(empty($b)){
$errors[]="b is empty";
}
if(empty($c)){
$errors[]="c is empty";
}
}...
如果数组中填充了$a
、$b
或$c
错误消息,我如何使用if (in_array('??'; $errors))
进行检查?
我知道这一点:
$errors = array(
'a' => 'Please enter a.',
'b' => 'Please enter b.',
'c' => 'Please enter c.'
);
在这里,我可以简单地用if (in_array('a'; $errors))
检查a
是否有一些错误消息。我遇到的问题是,对于a、b或c,我不仅有一条错误消息。因此,我正在寻找一种将这两种方法结合在一起的方法:
$errors = array(
'a' => if ( empty ($a) || $specific_error1_for_a || $specific_error2_for_a ),
'b' => if ( empty ($b) || $specific_error1_for_b || $specific_error2_for_b ),
'c' => if ( empty ($c) || $specific_error1_for_c || $specific_error2_for_c ),
);
我正在寻找一种方法来在数组errors[]
中搜索这些元素a,b
或c
中每一个的失败消息实例。
主要的问题是,我希望有一个变量或其他东西,当使用in_array时可以搜索。更具体地说:
我的每个输入字段都有一个错误层。因此,如果特定输入字段存在特定错误消息,我需要搜索整个阵列errors[]
:
<input type="text" id="a" name="a" value="<?php echo isset ($_POST['a'])? $_POST['a'] : ''; ?>" tabindex="10" autocomplete="off"/><?php if (**in_array(...., $errors)**):?><span class="error"><?php echo $errors['a'];?></span><?php endif;?>
问题是,正如我已经说过的,我对每个输入字段只有不止一个错误消息实例,所以我会有这样的东西:
(**in_array('a is empty' || 'a is too short' || 'a is too long' ..., $errors)**)
这就是为什么我认为最好只搜索一个这样的变量:
(**in_array($a, $errors)**)
如果有人能就此给我建议,我将不胜感激。非常感谢。
array_intersect
可以像in_array
一样用于多个值:
if(array_intersect($errors, array(
'a is empty',
'specific_error1_for_a',
'specific_error2_for_a',
))) {
// There is an error for a
}
不过,我建议您以不同的方式设计程序。如果您首先将错误存储在关联数组中,那么检查给定变量是否有任何错误会变得更有效率:
if(empty($a)){
$errors['a'][]="a is empty";
}
if(empty($b)){
$errors['b'][]="b is empty";
}
if(empty($c)){
$errors['c'][]="c is empty";
}
if(isset($errors['a'])) {
// There is an error for a
}