This "Undefined offset: 0" error keeps showing in my console , Is this wrong code for mt_rand? PHP: $game= $levelArena->getPlayers(); $selected = mt_rand(0, count($game) - 1); $selected->sendMessage("Test");
Yes because $selected is an int datatype and not a Player instance. Your code should be changed into: PHP: $game = $levelArena->getPlayers();$selected = $game[mt_rand(0, count($game) - 1)];$selected->sendMessage("Test");
Assuming $levelArena is a Level instance, that's an invalid way to select a random value from $levelArena->getPlayers(). Why? Whenever a Player instance is added to a level, the Level instance stores the Player instance mapped to their entity ID. PHP: Level::$players = [ $player->getId() => $player]; That makes the array non-sequential. mt_rand(0, count(Level::$players) - 1) should only be used for sequential arrays. PHP: /** * Returns random element from $array */function getRandomElement(array $array){ return $array[mt_rand(0, count($array) - 1)];}$array = [];$array[] = "element1";$array[] = "element2";echo getRandomElement($array);//no errors.$array = [];$array[2] = "element1";$array[7] = "element2";echo getRandomElement($array);//error Use array_rand() in combination with @Primus's reply (array_rand() throws errors for empty arrays). PHP: /** @var Player[] $game *//** @var Player $selected */$selected = $game[array_rand($game)];