我有以下数组:
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";
}
}...
如何用
if (in_array('??'; $errors))
检查数组中是否填充了$a
,$b
或$c
错误消息?我知道这种方式:
$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
}
关于php - PHP in_array检查数组的最佳方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11577046/