What are some common methods for dynamically changing the background color of navigation elements based on the current page in PHP?

To dynamically change the background color of navigation elements based on the current page in PHP, you can use a combination of PHP and CSS. One common method is to add a class to the navigation element that corresponds to the current page, and then use CSS to style that class with a different background color. This can be achieved by checking the current page URL against the navigation links and adding a class dynamically.

<?php
$current_page = basename($_SERVER['PHP_SELF']);
?>
<!DOCTYPE html>
<html>
<head>
    <style>
        .active {
            background-color: #f00; /* Change this to the desired background color */
        }
    </style>
</head>
<body>
    <ul>
        <li <?php if($current_page == 'index.php') echo 'class="active"'; ?>><a href="index.php">Home</a></li>
        <li <?php if($current_page == 'about.php') echo 'class="active"'; ?>><a href="about.php">About</a></li>
        <li <?php if($current_page == 'services.php') echo 'class="active"'; ?>><a href="services.php">Services</a></li>
        <li <?php if($current_page == 'contact.php') echo 'class="active"'; ?>><a href="contact.php">Contact</a></li>
    </ul>
</body>
</html>