开发者

Check if PHP variables are hold unique values

I have 20 variables, each holding a number between 1 and 10000.

Is there a开发者_C百科 simple way of checking that all of the variables hold a unique value, and if not sending the user away.

for example,

if($var1,$var2,$var3...etc are not unique)
{
location wherever.php
exit;
}

The front end should prevent the user submitting the same value twice however I need to check it.

Thanks :)


$data   = array( /* your numbers */);
$unique = array_unique($data);

if ( count($data) != count($unique) ) {
  // not unique
}

You can also compare that arrays instead of counting their elements:

if ( $data != $unique ) {
  // not unique
}


Put the values in an array.

Pass the array to the php function

array array_unique ( array $array [, int $sort_flags = SORT_STRING ] )

If the array returned by the function is smaller then the input then it found non unique keys.


$arr = array($var1, $var2 ... );
$arr2 = array_unique($arr);

if(count($arr) != count($arr2)){
   // send location;
}


i would make a function that uses array_unique()

like this:

function is_unique($array) {
    if (count(array_unique($array)) < count($array)) return false;
    return true;
}

then you have to use headers to redirect the client from php:

if (!is_unique($array)) {
    header("location: whatever");
}

note that headers must be sent before any html code. If you cant do that you have to use javascripts window.location = url to redirect the client


It would be very easy if the variable where in an array.

$var[1] = 590;
$var[2] = 614;

etc etc

Then you can do:

foreach ($var as $a_key => $a){
     foreach($var as $b_key => $b){
      if($a==$b && $a_key != $b_key){
         //Do whatever you want to do. 
      }
     }
}

This method will allow you to perform a function on each matching pair, or as a response to each matching pair.


Put each of the variables into an array $variables = array( $var1, $var2 , ... )

sort($variables)
$before = null;
foreach($var as $variables) {
     if ($before = $var) { // $var is not unique
         header("Location: whereever.php");
         die();
     }
     $before = $var;
}
// if you reach this point, all variables were unique
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜