Marwane Bettach Marwane Bettach - 2 months ago 11
PHP Question

php variable based on a random variable

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";

?>

Answer
$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);
Comments