Wednesday, 26 August 2020

PHP Program Find Intersection between Two array

PHP Program Find Intersection between Two array

Create PHP  function FindIntersection(strArr) read the array of strings stored in strArr which will contain 2 element

 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. 

Your function should 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.


Solution:

  function FindIntersection($strArr) {
    $return ='false';  
    $array1 = explode(',',$strArr[0]);
    $array1= array_map('trim',$array1);

    $array2 = explode(',',$strArr[1]);
    $array2= array_map('trim',$array2);

    $result= array_intersect($array1,$array2);
    if(!empty($result)){
      $return=implode(',',$result);  
    }

  return $return;

}