How can PHP be used to handle ranking ties in database outputs?

When dealing with ranking ties in database outputs, one approach is to assign a unique rank to each row and handle ties by adjusting the ranking accordingly. This can be achieved by using a combination of SQL queries to retrieve the data and PHP logic to calculate the ranks.

<?php
// Connect to the database
$pdo = new PDO('mysql:host=localhost;dbname=your_database', 'username', 'password');

// Retrieve the data from the database
$stmt = $pdo->query('SELECT * FROM your_table ORDER BY score DESC');
$rows = $stmt->fetchAll();

// Initialize rank counter
$rank = 1;

// Loop through the rows and handle ties
foreach ($rows as $key => $row) {
    if ($key > 0 && $row['score'] < $rows[$key - 1]['score']) {
        $rank = $key + 1;
    }

    // Output the row with the rank
    echo "Rank: $rank - Name: {$row['name']} - Score: {$row['score']} <br>";
}
?>