Blake Morgan
Blake Morgan

Reputation: 775

Comparing Array Values in For Loop (PHP)

I have a for loop and I want to compare each value to the other values in the array. If there are duplicates, the page redirects. How can I compare the value $name[$x] to the other values in the $name array whether or not they come before or after $name[$x]?

for($x=0; $x<4; $x++) {
    if($name[$x] == /*Other members of $name*/) {
        header("location:../error/duplicates.php");
        exit;
    }
}

Upvotes: 1

Views: 1825

Answers (2)

Giacomo1968
Giacomo1968

Reputation: 26066

Why are you doing it like this:

for($x=0; $x<4; $x++) {
    if($name[$x] == /*Other members of array*/) {
        header("location:../error/duplicates.php");
        exit;
    }
}

When you could be use array_unique instead:

if (count(array_unique($name)) < count($name)) {
  header("location:../error/duplicates.php");
  exit;
}

The logic is basically, the array_unique tells you how many unique items are in an array, right? And if the $name array contains 4 items, count(array_unique()) should return 4. Which then should match the count() of the items in $name, right? Well, if count(array_unique()) has less items than count() it means duplicates were filtered out.

Here it is without the header but an echo instead as well as an else for simpler debugging.

$name = array('bob','betty','dan','don'); // no dupes
$name = array('bob','betty','dan','dan'); // dupes

if (count(array_unique($name)) < count($name)) {
  echo 'Dupes!';
  exit;
}
else {
  echo 'No Dupes!';
}

Also you could use array_diff_key with array_unique. Basically do an array_unique on $name and then run that through array_diff_key comparing it to the original $name. if the count is greater than 0 then there is a dupe.

$name = array('bob','betty','dan','don'); // no dupes
$name = array('bob','betty','dan','dan'); // dupes

$name_diff = array_diff_key($name, array_unique($name));
if (count($name_diff) > 0) {
  echo 'Dupes!';
  echo '<pre>';
  print_r($name_diff);
  echo '</pre>';
  exit;
}
else {
  echo 'No Dupes!';
}

EDIT I just edited the last suggestion to use a variable for $name_diff since if it does return a value more than 0 you now have that value in an array & can act on it.

Upvotes: 3

Krish R
Krish R

Reputation: 22711

Can you try this, You can use in_array php function

if (in_array($name[$x], $yourarray)) {
    echo $name[$x] ." Exist";
 }

For duplicate check:

 if(count($yourarry)> count(array_unique($name))){
    //found duplicate
 }

Upvotes: 1

Related Questions