What are some best practices for dynamically changing the background color of a cell in a table based on a condition in PHP?

To dynamically change the background color of a cell in a table based on a condition in PHP, you can use inline styling within the HTML output. You can check the condition within a loop that generates the table rows, and set the background color style attribute accordingly.

<?php
// Sample data
$data = [
    ['name' => 'John', 'age' => 25],
    ['name' => 'Jane', 'age' => 30],
    ['name' => 'Alice', 'age' => 20]
];

// Output table with dynamically changing background color based on age
echo '<table>';
foreach ($data as $row) {
    $backgroundColor = ($row['age'] > 25) ? 'background-color: #ff0000;' : 'background-color: #00ff00;';
    echo '<tr style="' . $backgroundColor . '">';
    echo '<td>' . $row['name'] . '</td>';
    echo '<td>' . $row['age'] . '</td>';
    echo '</tr>';
}
echo '</table>';
?>