PHP比较变量[关闭]

I have many variables sent from a voting form. i want to check and make sure no two values on the form are equal. How can i do this?

<?php
$Name = $_POST['name'];
$ID = $_POST['id'];
$Topic_1 = $_POST['1'];
$Topic_2 = $_POST['2'];
$Topic_3 = $_POST['3'];
$Topic_4 = $_POST['4'];
$Topic_5 = $_POST['5'];
$Topic_6 = $_POST['6'];
$Topic_7 = $_POST['7'];
$Topic_8 = $_POST['8'];
$Topic_9 = $_POST['9'];
$Topic_10 = $_POST['10'];
$Topic_11 = $_POST['11'];
$Topic_12 = $_POST['12'];
$Topic_13 = $_POST['13'];
$Topic_14 = $_POST['14'];
$Topic_15 = $_POST['15'];

if($_POST != $_POST)???

You can easily determine if any array contains duplicate values with the construct

if (count($array) === count(array_unique($array))) {
    // contains duplicates
}

This is true for any array, including $_POST. So if you want to make sure that all 15 fields plus the name and id are unique with respect to one another, substitute $_POST for $array above and you are good to go.

There are a few more things you might want to keep in mind here:

  1. If it's possible that some of the form elements will be left blank and you are OK with allowing multiple blank fields then you need to remove them from the array before making the duplicate check. This can be done with (just one possible way):

    $array = array_filter($array, function($i) { return strlen($i); });
    
  2. If you want to look for duplicate among only a subset of the form elements, then the most consequent way is to make this subset an array of its own. You can have PHP do this automatically for you by naming the form input elements appropriately.

  3. Related to the concept of uniqueness is the function array_count_values, which can be useful in similar circumstances (it can tell you how many duplicate elements there were and exactly what their value was).

$_POST != $_POST

would definitely not work, cause this tests if the same variable is not the same variable.

You have to loop trough the $_POST array

<?php
foreach($_POST as $key => $value) {
    foreach($_POST as $subKey => $subValue) {
        if($key != $subKey && $_POST[$key] == $_POST[$key])
            return false;
    }
}

What you looking for is following

$_POST['1'] = 'a';
$_POST['2'] = 'b';
$_POST['3'] = 'c';
$_POST['4'] = 'a';
$_POST['5'] = 'd';

$results = array_unique($_POST);
var_dump($results);

returns:

array
  1 => string 'a' (length=1)
  2 => string 'b' (length=1)
  3 => string 'c' (length=1)
  5 => string 'd' (length=1)