Compare repeat values on five variables at the same time

Asked

Viewed 38 times

1

I would like a little help. I have a small web form where people should select 5 options in HTML SELECT fields. When submitting the form, I have to check if any of the filled out (it is optional to fill in, but if you fill in, you cannot repeat) is repeated. If any option repeats, I have to treat and show an error. If all are unique I save the information in the database. Follows structure of my php:

$var1 = isset($_POST["id_variante1"]) ? $_POST["id_variante1"] : "";
$var2 = isset($_POST["id_variante2"]) ? $_POST["id_variante2"] : "";
$var3 = isset($_POST["id_variante3"]) ? $_POST["id_variante3"] : "";
$var4 = isset($_POST["id_variante4"]) ? $_POST["id_variante4"] : "";
$var5 = isset($_POST["id_variante5"]) ? $_POST["id_variante5"] : "";

Is there any simple way to check if any of them other than "empty" repeats?

Editing:

Editing:

The simplest way I found was this, mixing the @Igor suggestion. It’s not the most practical thing in the world, but it works for what I need:

$teste = array_filter($_POST["id_variante[]"]);
if(count(array_unique($teste))<count($teste))
{ 
echo "há duplicatas" 
} else { 
echo "não há duplicatas" }

1 answer

1

Something I think might work:

$var = array(5);

$var[0] = isset($_POST["id_variante1"]) ? $_POST["id_variante1"] : "";
$var[1] = isset($_POST["id_variante2"]) ? $_POST["id_variante2"] : "";
$var[2] = isset($_POST["id_variante3"]) ? $_POST["id_variante3"] : "";
$var[3] = isset($_POST["id_variante4"]) ? $_POST["id_variante4"] : "";
$var[4] = isset($_POST["id_variante5"]) ? $_POST["id_variante5"] : "";

Then you compare the values in the positions of these arrays, of course it would not be the perfect way to do it, but it can work.

  • I have already thought about this solution, even send as an array with id_variant[]. So far the simplest solution I found was this: $teste = array_filter($_POST["id_variante[]"]);&#xA;if(count(array_unique($teste))<count($teste)) { echo "há duplicatas" } else { echo "não há duplicatas" }

Browser other questions tagged

You are not signed in. Login or sign up in order to post.