jeudi 18 juin 2020

Weird behavior with foreach() with PHP\array_rand(x, y)

I am trying to randomly assign attributes to an entity by selecting k item from a vector of n items. On running the below snippet, sometimes it works, sometimes It gives this weird error with foreach

InvalidForeachArgumentException: Invalid argument supplied for foreach()

I did read about a few posts about a weird behavior with foreach when a variable is passed by reference and there might be a need to unset it but that seems unrelated to this as I am not using any reference here. Funny thing is if I don't generate $factor using a random number generator but set it to a constant integer value, the code just works. I am not really sure, what's happening here.

$factor = PseudoRandom\int(
          1,
          $num
        );

        $capabilities = vec[];
        $random_keys = PHP\array_rand(
          $temp,
          $factor, 
        );

        foreach ($random_keys as $key) {
          $capabilities = Vec\append(
            $capabilities,
            $temp[$key],
          );
        }



Aucun commentaire:

Enregistrer un commentaire