Jump to content

Finding out a winner from numbers


Mutley

Recommended Posts

I have a little script that finds out a winner and a loser between 2 people:

 

$player1 = 'bob;
$player2 = 'dave';
$p1_points = '7';
$p2_points = '9';

		if($p1_points > $p2_points) {
			$winner = $player1;
			$loser = $player2;
			} elseif($p1_points < $p2_points) {
			$winner = $player2;
			$loser = $player1;
			}
echo "1st = $winner and 2nd = $loser;

1st = dave and 2nd = bob

 

So very simple. However, if I have 6 players, ($p1_points, $p2_points, $p3_points, $p4_points, $p5_points and $p6_points), how would I find out, not only a winner but in order of, 1st/2nd/3rd/4th and 5th place? Would it be some sort of array?

 

Link to comment
https://forums.phpfreaks.com/topic/48966-finding-out-a-winner-from-numbers/
Share on other sites

Like this could be one way:

 

<?php

$players = array("12" => "Bob", "25" => "Dave", "1" => "Tim", "6" => "Roy");

sort($players);
$run = 1;
foreach($players as $score => $name){
if($run == 1){
	echo "WINNER: $name, SCORE: $score<br>"; 
}else{
	echo "NAME: $name, SCORE: $score<br>";
}
$run++;
}

?>

<?php
function ordinal($cdnl)
    {
    $test_c = abs($cdnl) % 10;
    $ext = ((abs($cdnl) %100 < 21 && abs($cdnl) %100 > 4) ? 'th'
            : (($test_c < 4) ? ($test_c < 3) ? ($test_c < 2) ? ($test_c < 1)
            ? 'th' : 'st' : 'nd' : 'rd' : 'th'));
    return $cdnl.$ext;
    } 
$players = array("12" => "Bob", "25" => "Dave", "1" => "Tim", "6" => "Roy");

krsort($players);
$run = 1;
foreach($players as $score => $name){
if($run == 1){
	echo ordinal($run).": $name, SCORE: $score<br>"; 
}else{
	echo ordinal($run).": $name, SCORE: $score<br>";
}
$run++;
}
?>

 

if you look at the above array, you will see number => name, number is a key value, and name is the value, so => points from the key to the value.

in the foreach it is saying give the key a variable of $score and the value a variable of $name, this is so you can use them within the loop.

Thanks but I still have problems, looking back at my original post I need it to find the top 3 players (from $player1, $player2, $player3, $player4, $player5, $player6) then set them new variables which I will use for a database query later on.

 

So it does this:

 

$first_player = $player4; // $player4 is example but whoever is 1st...

$second_player = $player2;

$third_player = $player3;

 

If that makes sense? What you have done is great and I have used that later on but for this part I just need raw variables.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.