Reputation: 25
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)
Upvotes: 0
Views: 54
Reputation: 350242
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"]
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.
foreach ($a as $x) { ... }
: $x is a value from the first array$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
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.return $c;
: return the result array to the callerUpvotes: 1