简体   繁体   中英

Comparing arrays and counting their values

How could I compare these arrays and count their values:

$arrayone = array("3", "2", "1", "2", "3");
$arraytwo = array("1", "2", "3", "2", "1");

My goal isn´t 3 (unique values) or 5 (same amount of values in general) but 4! The second array contains one 1 too much, how can i get a new array like this:

$arraythree = array("1", "2", "3", "2");

This is giving me 3 unique values:

$intersect = array_intersect($arrayone, $arraytwo);
$arraythree = array_unique($intersect);
count($arraythree)

This is giving me 5 non-unique values:

$arraythree = array_intersect($arrayone, $arraytwo);
count($arraythree)

You could use this custom function:

function myIntersect($a, $b) {
    foreach ($a as $x) {
        $i = array_search($x, $b);
        if ($i !== false) {
            $c[] = $x;
            unset($b[$i]);
        }
    }
    return $c;
}

How to use:

$arrayone = array("3", "2", "1", "2", "3");
$arraytwo = array("1", "2", "3", "2", "1");
$result = myIntersect($arrayone, $arraytwo);
print_r($result); // ["3", "2", "1", "2"]

Explanations

The idea is to take each value from the first array and find the first position where it occurs in the second. If found, then it is copied into the result, and the matching value in the second array is erased at the found position, so it cannot be matched again.

  1. foreach ($a as $x) { ... } : $x is a value from the first array
  2. $i = array_search($x, $b); : $i is the first position where the value occurs in the second array, or if not found, $i is false
  3. if ($i !== false) { : if the search was successful...
    • $c[] = $x; : then add the value to the result array $c and...
    • unset($b[$i]); : ...remove it from the found position in $b . Note that in PHP the arrays passed to the function are in fact copies of the original arrays, so such removals have no effect on the original arrays that were passed to the function.
  4. Repeat previous steps for all values in the first array
  5. return $c; : return the result array to the caller

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM