Member-only story
Have the function FindIntersection(strArr)
read the array of strings stored in strArr
which will contain 2 elements: the first element will represent a list of comma-separated numbers sorted in ascending order, the second element will represent a second list of comma-separated numbers (also sorted). Your goal is to return a comma-separated string containing the numbers that occur in elements of strArr
in sorted order. If there is no intersection, return the string false.
<?phpfunction FindIntersection($strArr) { $array1 = explode(", ", $strArr[0]); $array2 = explode(", ", $strArr[1]); $intersect = []; foreach ($array1 as $data) {
if (in_array($data, $array2)) { $intersect[] = $data;
} } return (empty($intersect)) ? "false" : implode(",", $intersect); return $strArr;}// echo the function call hereecho FindIntersection();?>output logs will look like this:1,4,13
The explode
function
is used to “Split a string into pieces of elements to form an array”, in simple term, it breaks a string into an array.