I have this code here:
<ul>
<li<?php if ($page == 'home') echo ' class="active' ?>><a href="index.php">Home</a></li>
<li<?php if ($page == 'contact') echo ' class="active' ?>><a href="pages/contact.php">Contact Us</a></li>
<li<?php if ($page == 'services') echo ' class="active' ?>><a href="pages/services.php">Services</a></li>
<li<?php if ($page == 'employees') echo ' class="active' ?>><a href="pages/employees.php">Employees</a></li>
<li<?php if ($page == 'dashboard') echo ' class="active' ?>><a href="pages/dashboard.php">Dashboard</a></li>
</ul>
But I would like to refactor it to pull out some of that repetition. I am working with arrays, and have it somewhere like this:
$pages = array(
"index.php" => "Home",
"contact.php" => "Contact Us",
"services.php" => "services",
"employees.php" => "Employees",
"dashboard.php" => "Dashboard");
foreach ($pages as $item) {
if (isset($_GET['page']) && $_GET['page'] == $item) {
echo 'class="active" ?><a href="' . array_keys($item) . '"> ' . array_values($item) . '</a></li>';
} else {
echo '<a href="' . array_keys($item) . '"> " . ' . array_values($item) . '</a></li>';}
I can't seem to make it work though. I want it to put the final line together for me add an active class to my nav bar tags when on that page and not otherwise. Is there a reasonable way to do this, and is it good practice?
<?php foreach (...):?>and<?php endforeach; ?>?