compare same array values

17,418

Solution 1

You can use array_count_values and in_array functions as:

if(in_array(2,array_count_values($array)) {
  // do something
}

Solution 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,

Solution 3

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)

Solution 4

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!')
Share:
17,418
ahmad
Author by

ahmad

Updated on August 28, 2022

Comments

  • ahmad
    ahmad over 1 year

    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 ?