Tests en Php

File Owners

Implement a groupByOwners function that:

  • Accepts an associative array containing the file owner name for each file name.
  • Returns an associative array containing an array of file names for each owner name, in any order.

For example, for associative array [« Input.txt » => « Randy », « Code.py » => « Stan », « Output.txt » => « Randy »] the groupByOwners function should return [« Randy » => [« Input.txt », « Output.txt »], « Stan » => [« Code.py »]].

<?php
function groupByOwners(array $files) : array
{
    $list = array();
    $groups = array_unique($files,SORT_REGULAR);
    foreach($groups as $group)
    {
   
      foreach ($files as $key => $value)
      {
          if($group==$value)
          {
              $list[$group][]=$key;
          }
         
      }
    }
    return $list;
}

$files = array
(
    "Input.txt" => "Randy",
    "Code.py" => "Stan",
    "Output.txt" => "Randy"
);
print_r(groupByOwners($files));

Merge Names

Implement the unique_names function. When passed two arrays of names, it will return an array containing the names that appear in either or both arrays. The returned array should have no duplicates.

For example, calling unique_names([‘Ava’, ‘Emma’, ‘Olivia’], [‘Olivia’, ‘Sophia’, ‘Emma’]) should return [‘Emma’, ‘Olivia’, ‘Ava’, ‘Sophia’] in any order.

<?php

function unique_names(array $array1, array $array2) : array
{
    $array_merge = array_merge($array1, $array2);
    $array_merge_unique = array_unique($array_merge);
    return$array_merge_unique;
}

$names = unique_names(['Ava', 'Emma', 'Olivia'], ['Olivia', 'Sophia', 'Emma']);
echo join(', ', $names); // should print Emma, Olivia, Ava, Sophia