Reputation: 189
I'm new to php
and I wrote a code that takes a random winner out of an array
and displays it, then I wanted to try to display all the names without the winner's, but how can I unset
the winner by using the random number generated? I managed to unset
a random name but not the same as the winner...
<?php
// array
$winner = array();
array_push($winner,"sonia");
array_push($winner,"ice");
array_push($winner,"sasha");
array_push($winner,"isa");
array_push($winner,"omar");
array_push($winner,"anwar");
// random winner
$giocatori = count($winner);
$random = rand(0,$giocatori -1);
unset($winner[$random]);
// Sort the list
sort($winner);
echo "I giocatori sono: ";
print join(", ",$winner);
// Print the winner's name in ALL CAPS
$truewinner = strtoupper($winner[$random]);
echo "<br><br>";
echo "il vincitore è: ";
// Print winner + sentence
$losers = "losers";
$losers = strtoupper($losers);
echo (strtoupper($winner[$random]));
echo "<br><br>";
echo "all the players are: $losers beside $truewinner";
?>
Upvotes: 1
Views: 436
Reputation: 296
How to write the array:
$participants = array("sonia", "ice", "sasha","isa","omar","anwar");
or
$participants = array();
$participants[] = "sonia";
$participants[] = "ice";
and soo on
//make all participants name first letter uppercase
$participants = array_map(function($string) {return ucfirst($string);},$participants);
To get an random value from the array you have:
//get a random key
$random = array_rand($participants);
//get the value for the key
$winner = $participants[$random];
//unset the key and value
unset($participants[$random]);
OR
//this will shuffle values in the array on random positions
shuffle($participants);
//this return the last value from the array and deletes it from the array
$winner = array_pop($participants);
echo "The winner is $winner !\n";
echo "The losers are ".implode(', ',$participants)."\n";
Upvotes: 1
Reputation: 2229
<?php
// array
$winner = array();
array_push($winner,"sonia");
array_push($winner,"ice");
array_push($winner,"sasha");
array_push($winner,"isa");
array_push($winner,"omar");
array_push($winner,"anwar");
// random winner
$giocatori = count($winner);
$random = rand(0,$giocatori -1);
echo "winner is".$winner[$random];
unset($winner[$random]);
// Sort the list
sort($winner);
echo print_r($winner) ;
echo "losers are ";
foreach($winner as $res) {
echo $res. ' ';
}
?>
winner is anwar
Array
(
[0] => ice
[1] => isa
[2] => omar
[3] => sasha
[4] => sonia
)
losers are ice isa omar sasha sonia
Upvotes: 0
Reputation: 24276
$players = array('sonia', 'ice', 'sasha', 'isa', 'omar');
$random = rand(0, count($players) - 1);
$winner = $players[$random];
$losers = array_diff($players, array($winner));
echo 'All players are: ' . implode(', ', $players);
echo 'Winner is: ' . $winner;
echo 'Losers are: ' . implode(', ', $losers);
Upvotes: 1