How do I pick a random player in a world?

Discussion in 'CommandHelper' started by MPKingJulian, Sep 24, 2017.

  1. MPKingJulian

    MPKingJulian New Member

    I am unsure how to pick a random player in a world.
    For example if I wanted one random player in a world to run a random command.

    Anyone got an example?
    TY
  2. PseudoKnight

    PseudoKnight Well-Known Member

    You can use rand() or array_rand(), depending on which syntax you prefer. Here's some examples, broken apart and combined.
    PHP:
    // using rand()
    @players = all_players(@world);
    @num = array_size(@players);
    if(@num > 0) {
      @r = rand(@num);
      @player = @players[@r];
    } else {
      // no players in world
    }

    // or combined.
    @players = all_players(@world);
    if(@players) {
      @player = @players[rand(array_size(@players))];
    } else {
      // no players in world
    }

    // using array_rand()
    @players = all_players(@world);
    if(@players) {
      @playerInArray = array_rand(@players, 1, false);
      @player = @playerInArray[0];
    } else {
      // no players in world
    }

    // somewhat combined
    @players = all_players(@world);
    if(@players) {
      @player = array_rand(@players, 1, false)[0];
    } else {
      // no players in world
    }

    // or fully combined
    try {
      @player = array_rand(all_players(@world), 1, false)[0];
    } catch(IndexOverflowException @ex) {
      // no players in world
    }
    Last edited: Sep 24, 2017