phprandomforeachhacklang

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],
          );
        }

Solution

  • When picking only one entry, array_rand() returns the key for a random entry. Otherwise, an array of keys for the random entries is returned.
    https://www.php.net/array_rand

    So, when $factor happens to be 1, only a single key is returned, which you can't iterate over with foreach.