How to use yield with array_unique?

Hi all!

I would like to know how I could use yield with array_unique

Here is a simple example (which does not work)


function get_datas() {
   $a = ['jjf', 'jjfj', 'kfdjkf', 'aa', 'aa'];
   foreach($a as $b)
   {
     $array = (yield $b);
     array_unique($array);
   }
}

Yield is just like return, only the function can be called multiple times in a loop because function execution does not stop. If all you are looking for is a unique array, it doesn’t seem like you would necessarily want to use the function shown in your question, but it would seem to me that you would use array_unique before the foreach loop.


function get_datas() {
   $a = ['jjf', 'jjfj', 'kfdjkf', 'aa', 'aa'];
   array_unique($a);
   foreach($a as $b)
   {
     yield $b;
   }
}

OK and can you tell me how I can convert this code with yield


/**
 * @return array
 */
function get_datas() {
    // Begin code ...
    $arrayLines = array();
    while (false !== $line = fgets($fileHandle)) {
        if  (!empty($line))
            $arrayLines[] = $line;
        else
            return array();
    }

    fclose($fileHandle);

    return $arrayLines;
}

Thanks!

Actually, I think your initial example should look more like this:

function get_datas() {
   $a = ['jjf', 'jjfj', 'kfdjkf', 'aa', 'aa'];
   foreach($a as $b)
   {
     yield $b;
   }
}  

$getDatas = get_datas();
$array = array();
foreach ($getDatas as $value)
{
  if (!in_array($value, $array))
    $array[] = $value;
}

Which really is pointless, because you could just use array_unique($a) and get the same result. Can you tell me what you are trying to accomplish with using yield? I’m having a hard time trying to figure out what you want your method to do differently.