I am trying to get this form to:
if any $_POST vars equals any other of the $_POST vars throw an error.
if it was just a few it wouldnt be an issue but I have about 20 or so so if i wanted to do it I would have to go like
<?php
if($_POST['input1']==$_POST['input2'] || $_POST['input1']==$_POST['input3']){
die('whatever');
}
?>
But that's not good coding (and it would take forever) I thought about arrays and different ways...
but I am brain dead atm so I thought I could get some help.. thanks in advance
ps开发者_如何学JAVA it would be nice to do it in PHP (server side) but Jquery is always an option.
Delete duplicate values with array_unique()
and check if it still equals to your array:
if($_POST != array_unique($_POST))
die("...");
if ($_POST == array_unique($_POST)) {}
function testPost(){
foreach ($_POST as $keya=>$vala){
foreach($_POST as $keyb=>$valb){
if ($keya==$keyb){
continue;
} else {
if ($vala == $valb){
return FALSE;
}
}
}
}
return TRUE;
}
This is only an answer to zebediah49's post. A more effective implementation would be:
$post = array_value($_POST);
$count = count($post);
for ($i = 0; $i < $count; ++$i) {
for ($j = $i + 1; $j < $count; ++$j) {
if ($post[$i] == $post[$j]) {
die();
}
}
}
This saves all the multiple checks. So it results in O(2*n) instead of O(n^2) (if I got that O stuff right). Though I don't know how much this is slowed down by the additional array_values
.
$postValues = array_values($_POST);
if (array_unique($postValues)) != $postValues) {
die('error!');
}
not so good, but
I'd say you have to do it in a double-loop; while it's O(n^2), it'll not be problematic in practice
foreach($_POST as $keya=>$vala) {
foreach($_POST as $keyb => $valb) {
if($vala == $valb && $keya != $keyb) {
die('whatever');
}
}
}
You can do:
$count_array = array_count_values($_POST);
foreach($_POST as $post) {
if($count_array[$post] >1 ) {
die();
}
}
This is my final code... so basically i'm putting the ones I want into an array
credits will go to @akellehe because his was the closest to my end result....
works great
$titles=array();
$num=1;
while($num!=15){
$set1='title'.$num;
$set2=$_REQUEST["title$num"];
$titles[$set1]=$set2;
unset($set1);
unset($set2);
$num+=1;
}
foreach($titles as $d => $p){
foreach($titles as $e =>$q){
if($p==$q && $d!=$e){
if(!empty($p)){
$_SESSION['error']='Duplicates not allowed!';
}
}
}
}
精彩评论