3

What is the best way to compare elments in the same array in PHP, so that if there are two elemets with the same values in array A, I can pass a function as argument to do somthing ?

1
  • Can you give an example of what the array looks like. And what do you want the function to do if dupes are found? Commented Dec 19, 2010 at 15:55

4 Answers 4

5

You can use array_count_values and in_array functions as:

if(in_array(2,array_count_values($array)) {
  // do something
}
Sign up to request clarification or add additional context in comments.

Comments

2

If you want to find all values that are duplicated in an array you could do something like this:

// Array to search:
$array = array('one', 'two', 'three', 'one');
// Array to search:
// $array = array('a'=>'one', 'b'=>'two', 'c'=>'three', 'd'=>'one');
// Temp array so we don't find the same key multipule times:
$temp = array();
// Iterate through the array:
foreach ($array as $key)
{
    // Check the key hasn't already been found:
    if (!in_array($key, $temp))
    {
        // Get an array of all the positions of the key:
        $keys = array_keys($array, $key);
        // Check if there is more than one position:
        if (count($keys)>1)
        {
            // Add the key to the temp array so its not found again:
            $temp[] = $key;
            // Do something...
            echo 'Found: "'.$key.'" '.count($keys).' times at position: ';
            for($a=0;$a<count($keys);$a++)
            {
                echo $keys[$a].','; 
            }                   
        }
    }
}

The output from the above would be:

Found: "one" 2 times at positions: 0,3,

If your array had custom keys (as in the commented array) the output would be:

Found: "one" 2 times at positions: a,d,

1 Comment

Changed the for loop, to a foreach, incase the array has custom keys instead of the default numerical key.
1

I assume you wan't to merge to array and then remove duplicates.

$array1 = array('a', 'b', 'c');
$array2 = array(1, 2, 3, 'a');

// array_merge() merges the arrays and array_unique() remove duplicates
var_dump(array_unique(array_merge($array1, $array2)));

// output: array('a', 'b', 'c', 1, 2, 3)

Comments

1

Use array_udiff or similar (with reference arguments in the callback, if you want to be able to modify the values):

$array1 = array('foo', 'bar', 'baz');
$array2 = array('foo', 'baz');

$result = array_udiff($array1, $array2, function(&$a, &$b) {
     if ($a == $b) {
         $a = $b = 'same!';
         return 0;
     }
     return $a > $b ? 1 : -1;
});

print_r($array1); // array('same!', 'bar', 'same!')
print_r($array2); // array('same!', 'same!')

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.