Code Challenge : Create a PHP function to find the intersection of two arrays - FirstDue Interview Questions
This was the client round question for code challenge..
Create a PHP function to find the intersection of two arrays.
<?php
function FindIntersection($strArr)
{
// Split the strings into arrays and convert to integers
foreach ($strArr as $index => $element) {
$strArr[$index] = array_map('intval', explode(',', $element));
}
$main_match_array = $strArr[0];
array_shift($strArr);
$interarray = [];
foreach ($strArr as $each_chunk) {
foreach ($main_match_array as $in => $number) {
if (in_array($number, $each_chunk)) {
$interarray[$number] = $number;
} else {
unset($interarray[$number]);
}
}
}
return implode(', ', $interarray);
}
echo '<pre>';
$result = FindIntersection(["10,2, 3", "6,3,8,2,10", "10"]);
echo $result; // Output: 1,4,13
echo "\n";
echo FindIntersection(["1, 3, 9,", "1, "]) . "\n"; // Output: 1
echo FindIntersection(["1, 2", "4","8"]) . "\n"; // Output: (empty)
Comments
Post a Comment