Home > database >  Issue with Generating Random Numbers using Laravel contains vs foreach loop
Issue with Generating Random Numbers using Laravel contains vs foreach loop

Time:04-29

Hey guys I come across this strange issue where if I use the foreach it does not generate a unique random number wheres if I use laravel function contains. it always generate a random number

I'm curious how this can happen

see my code below

          #Main Function subscribers are an eloquent collection 
          
         foreach ($this->subscribers as $subscriber){
            $subscriber->drawOrder = $this->generateRandomNumbers();
         }

         dd($this->subscribers->pluck('drawOrder'));

    }


    public function generateRandomNumbers()
    {

        $number = mt_rand(1, count($this->subscribers));

        if ($this->checkIfUserHasDraw($number)) {
            return $this->generateRandomNumbers();
        }

        return $number;
    }

    public function checkIfUserHasDraw($number)
    {

      //return $this->subscribers->contains('drawOrder', $number);

        foreach ($this->subscribers as $user) {
            return $user->drawOrder == $number;
        }
    }

Output

0 => 3
1 => 5
2 => 1
3 => 5
4 => 1

Where's if I use the commented contains method it comes with unique random values

This is strange. Any thoughts on this is really helpful

CodePudding user response:

In the foreach it only checks the first user as you immediately return, the following would work:

public function checkIfUserHasDraw($number)
{
    foreach ($this->subscribers as $user) {
        if ($user->drawOrder == $number) {
            return true;
        }
    }
    return false;
}

But the contain does pretty much the same, so I would use that.

  • Related