Ross
Ross

Reputation: 21

Check if PHP variables are hold unique values

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

Is there a 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 :)

Upvotes: 2

Views: 3649

Answers (6)

Artog
Artog

Reputation: 1142

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

Upvotes: 1

ShiningRay
ShiningRay

Reputation: 1008

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

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

Upvotes: 1

hsz
hsz

Reputation: 152216

$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
}

Upvotes: 10

Alex
Alex

Reputation: 34978

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

Upvotes: -1

Mild Fuzz
Mild Fuzz

Reputation: 30671

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.

Upvotes: 0

Pim Reijersen
Pim Reijersen

Reputation: 1133

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.

Upvotes: 9

Related Questions