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;

}
  

PHP Program Longest Word from the string

PHP Program Longest Word from the string

 Create PHP function LongestWord(sen) take the sen parameter being passed and return the largest word in the string.

If there are two or more words that are the same length, return the first word from the string with that length. 

Ignore punctuation and assume sen will not be empty.




Solution: 


function LongestWord($sen) {
    $return = '';

    //Convert string into Array
    $strArrayList = explode(' ', $sen);
    $finalArray = array();

    ///////Filter the words///////////
    foreach($strArrayList as $str){
        $str = preg_replace("#[[:punct:]]#", "", $str);
        $finalArray[] = $str;
    }
    ///////Filter the words///////////
    
    /////////// Get the First word  from the string with that length////////
    foreach($finalArray as $word){
        if(strlen($word)> strlen($return)){
        $return = $word;
        }
    }
    /////////// Get the First word  from the string with that length////////
    
    
    return $return;

}