How can one address the issue of using different stylesheets for different pages in PHP?
Issue: One way to address the issue of using different stylesheets for different pages in PHP is to create a function that dynamically includes the appropriate stylesheet based on the current page being accessed. This can be achieved by setting up a mapping of page names to stylesheet filenames and then using this mapping to include the correct stylesheet in the HTML header of each page.
<?php
// Define a mapping of page names to stylesheet filenames
$stylesheets = [
'home' => 'home.css',
'about' => 'about.css',
'contact' => 'contact.css'
];
// Function to include the appropriate stylesheet based on the current page
function includeStylesheet($page, $stylesheets) {
if(array_key_exists($page, $stylesheets)) {
echo '<link rel="stylesheet" type="text/css" href="' . $stylesheets[$page] . '">';
} else {
echo '<link rel="stylesheet" type="text/css" href="default.css">';
}
}
// Usage example: call includeStylesheet() in the <head> section of each page
$page = 'home'; // Change this to match the current page
?>
<!DOCTYPE html>
<html>
<head>
<title>My Website</title>
<?php includeStylesheet($page, $stylesheets); ?>
</head>
<body>
<!-- Page content goes here -->
</body>
</html>