Skip to content
PHP Logo

What potential issue arises when using multiple elseif statements in PHP for background color changing?

When using multiple elseif statements for background color changing in PHP, a potential issue is that only one condition will be met and the rest will be ignored. To solve this, you can use a series of if statements instead of elseif to check each condition independently and change the background color accordingly.

php
$hour = date('G');

if ($hour < 12) {
    $background_color = "lightblue";
}

if ($hour >= 12 && $hour < 18) {
    $background_color = "lightgreen";
}

if ($hour >= 18) {
    $background_color = "lightpink";
}

echo "<body style='background-color: $background_color'>";