Sukhchain Singh Sukhchain Singh - 12 days ago 5
PHP Question

Cross check if multiple variable are equal in php

Is there any efficient way to check these multiple variable values with each other?

Example: If value of

$v1
is abc and value of
$v2
is abc and other variables are empty then return error because two values are same.

Another Example: If value of
$v1
is abc and value of
$v4
is abc and other variables are empty then return error because two values are same.

Like check every variable with every other variable, if it's same with anyone then return an error.

$v1 = $_POST['v1'];
$v2 = $_POST['v2'];
$v3 = $_POST['v3'];
$v4 = $_POST['v4'];
$v5 = $_POST['v5'];
$v6 = $_POST['v6'];

Answer
$v1 = 1;
$v2 = 2;
$v3 = 3;
$v4 = 4;
$v5 = 5;
$v6 = 5;
$values = [$v1, $v2, $v3, $v4, $v5, $v6];
if (count($values) !== count(array_unique($values))) {
    echo 'Duplicates found';
}

DEMO

UPDATED

You can easily use array_count_values function to determine which values are duplicated. I put it here: http://phpio.net/s/16bh

Comments