A string array “F1” has got names of Facebook users and their friend association.</p>

 
<p>For example if we write: U1,U2 it implies that U1 is a friend of U2. This also implies that U2 is a friend of U1.</p>
 
<p> </p>
 
<p>Write a program which will read “F1”, remove duplicates, write all the unique pairs to “F2” array and finally return the “F2” array.</p>
 
<p>But, before removing duplicates <em>sort the input array based on the 0th index in alphabetical order</em></p>
 
<p> </p>
 
<p>For example, if the input “F1” might have the following data: </p>
 
<p>Input String =&gt; ["U1,U2","U3,U4","U2,U1","U1,U5"]</p>
 
<p>Output String =&gt; ["U1,U2","U1,U5","U3,U4"]
 
 
Answer:
 
    <?php
 
        // define array 
    $myArray = ["U1,U2","U3,U4","U2,U1","U1,U5"]; 
   
print_r(arrayUnique($myArray));
function arrayUnique($myArray)
{
    $newArray = Array();
    if (is_array($myArray))
    {
        foreach($myArray as $key=>$val)
        {
            if (is_array($val))
            {
                $val2 = arrayUnique($val);
            }
            else
            {
                $val2 = $val;
                $newArray=array_unique($myArray);
                $newArray=deleteEmpty($newArray);
                break;
            }
            if (!empty($val2))
            {
                $newArray[$key] = $val2;
            }
        }
    }
    return ($newArray);
}
 
 
 
function deleteEmpty($myArray)
{
    $retArray= Array();
    foreach($myArray as $key=>$val)
    {
        if (($key<>"") && ($val<>""))
        {
            $retArray[$key] = $val;
        }
    }
    return $retArray;
}
 
 
 
 
 
    ?>
 
Output:
 Array
(
    [1] => U3,U4
    [2] => U2,U1
    [3] => U1,U5
)
 
 
Share on Facebook