// Given two integer arrays nums1 and nums2, return an array of their intersection.
// Each element in the result must be unique and you may return the result in any order.
function intersection($nums1, $nums2) {
// firstly, remove duplicates,
// you can use here array_unique function twice !
$result1 = [];
$result2 = [];
foreach ($nums1 as $num1) {
if (!in_array($num1, $result1)) {
$result1[] = $num1;
}
}
foreach ($nums2 as $num2) {
if (!in_array($num2, $result2)) {
$result2[] = $num2;
}
}
// merge two arrays
// you can use here array_merge function !
for ($i = 0; $i < count($result2); $i++) {
$result1[$i + count($result1)] = $result2[$i];
}
$array = [];
// unfortunately, I could not count the values and
// get the keys from array without built-in function
$result1 = array_count_values($result1);
foreach ($result1 as $key => $value) {
if ($value >= 2) {
$array[] = $key;
}
}
return $array;
}
print_r(intersection([4, 9, 5], [9, 4, 9, 8, 4])); // [4, 9];
// Instead of so much effort, you can just use the array_intersect() function.