Compare the same array values

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

+3
source share
4 answers

You can use array_count_valuesand in_arrayperform functions:

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

If you want to find all the values ​​that are duplicated in an array, you can 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 conclusion from the above will be:

Found: "one" 2 times in the positions: 0.3,

If your array had user keys (as in a commented array), the output will be:

: "" 2 : a, d,

+2

, , .

$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)
+1

Use array_udiff or similar (using the referenced arguments in the callback if you want to change 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!')
+1
source

Source: https://habr.com/ru/post/1781114/


All Articles