Home > OS >  How do I loop through an Array, and remove the key with lowest value
How do I loop through an Array, and remove the key with lowest value

Time:10-16

I'm trying to make a program that has different players in an array assigned with random numbers. It is round-based, so every round the players are assigned new random numbers, and the player(s) with the lowest number is removed from the array.

Problem is that when iterating it doesn't remove the player with the lowest number from the array. It does however print out the player with the lowest number, but that's it...

I want it to remove the player or players and display their names each round till there is one left.

I'm new to learning PHP, so my code structure is not the best xd

$players = array(
    
    "Peter" => "0",
    "John" => "0",
    "Harold" => "0",
    "Alexander" => "0",
    "Thor" => "0",
    "Paul" => "0",
    "Jimmy" => "0",
    "Erik" => "0",
    "Donald" => "0",
    "Matthew" => "0"
);

    for($i = 0; $i < count($players); $i  ){
    
            echo "<br>" . "<b>Round ". (1   $i) ."</b><br>";
    
            foreach($players as $key => $value){
               
                //generating random number to value 
                $value = rand(1,50);
               
                asort($players);  
    
                //Assigning each player a random number
                $players[$key]=$value; 
    
    
                $min = min($players);
                 
                array_splice($players,$min));    
                
            }
            
            echo "Player(s) with lowest number is: " .current(array_keys($players, min($players)));
            echo "<br>"
        }

CodePudding user response:

Instead of use for-loop i suggest you to use while like:

$players = array(
    "Peter" => "0",
    "John" => "0",
    "Harold" => "0",
    "Alexander" => "0",
    "Thor" => "0",
    "Paul" => "0",
    "Jimmy" => "0",
    "Erik" => "0",
    "Donald" => "0",
    "Matthew" => "0"
);
$round = 1;
while (count($players) > 1) {
    echo "<br>" . "<b>Round " . $round . "</b><br>";

    foreach ($players as $key => $value) {    
        do {
            $value = rand(1, 50);
        } while(in_array($value, $players));
        $players[$key] = $value;
    }
    $key = array_keys($players, min($players))[0];
    echo "Player(s) with lowest number is: " . $key;
    echo "<br>";
    unset($players[$key]);
    $round  ;
}
echo '<br>The winner is:'. key($players);

What have I changed?

  • Use while with logic "continue while untile array count is one" (so just the winner
  • Use do-while for generate different number for each player (unique number)
  • find the min() of array then unset it.

Reference:

  • Related