What are the best practices for sorting arrays in PHP when the data is retrieved from a MySQL database and needs to be displayed in a specific order?

When retrieving data from a MySQL database in PHP and needing to display it in a specific order, the best practice is to use the ORDER BY clause in your SQL query to sort the data directly in the database query itself. This way, the data is already sorted when retrieved, saving processing time in PHP.

// Connect to MySQL database
$conn = new mysqli($servername, $username, $password, $dbname);

// Query to retrieve data from database in a specific order
$sql = "SELECT * FROM your_table ORDER BY column_name ASC";
$result = $conn->query($sql);

// Loop through the sorted data and display it
if ($result->num_rows > 0) {
    while($row = $result->fetch_assoc()) {
        echo "ID: " . $row["id"] . " - Name: " . $row["name"] . "<br>";
    }
} else {
    echo "No results found";
}

// Close database connection
$conn->close();