How can we optimize the code to improve performance when retrieving the highest result for each person in PHP?

The issue with the current code is that it loops through all results for each person to find the highest one, which can be inefficient for a large dataset. To optimize this, we can use a more efficient approach by querying the database to retrieve only the highest result for each person using a GROUP BY clause.

// Connect to the database
$connection = new PDO("mysql:host=localhost;dbname=your_database", "username", "password");

// Query to retrieve the highest result for each person
$query = "SELECT person_id, MAX(result) AS highest_result FROM results_table GROUP BY person_id";

// Execute the query
$statement = $connection->query($query);

// Fetch the results
$results = $statement->fetchAll(PDO::FETCH_ASSOC);

// Output the highest result for each person
foreach ($results as $row) {
    echo "Person ID: " . $row['person_id'] . " - Highest Result: " . $row['highest_result'] . "<br>";
}