1. The forums will be archived and moved to a read only mode in about 2 weeks (mid march).

Solved mt_rand Undefined offset: 0

Discussion in 'Development' started by Mystic30, May 20, 2018.

  1. Mystic30

    Mystic30 Witch

    Messages:
    52
    GitHub:
    Mystic30
    This "Undefined offset: 0" error keeps showing in my console , Is this wrong code for mt_rand?
    PHP:
    $game$levelArena->getPlayers();
                                                                            
    $selected mt_rand(0count($game) - 1);
                                                                            
    $selected->sendMessage("Test");
     
  2. Flavius12

    Flavius12 Spider Jockey

    Messages:
    32
    GitHub:
    flavius12
    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(0count($game) - 1)];
    $selected->sendMessage("Test");
     
    Primus likes this.
  3. Mystic30

    Mystic30 Witch

    Messages:
    52
    GitHub:
    Mystic30
    Same error occured
     
  4. Primus

    Primus Zombie Pigman

    Messages:
    749
    PHP:
    if(!empty($game)) {
     
    Muqsit likes this.
  5. Muqsit

    Muqsit Chicken

    Messages:
    1,548
    GitHub:
    muqsit
    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(0count($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)];
     
    OnTheVerge, Thunder33345 and Mystic30 like this.
  6. Mystic30

    Mystic30 Witch

    Messages:
    52
    GitHub:
    Mystic30
    Okay, Thanks everyone! :)
     
  1. This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
    By continuing to use this site, you are consenting to our use of cookies.