Trying to make the current page on the site highlighted:

<div id="nav"> <ul> <li> <a <?php echo ($_GET['page'] == 'index' || !isset($_GET[page])) ? "class='active'" : ""; ?> href="index1.php">Главная</a> </li> <li> <a <?php echo ($_GET['page'] == 'news') ? "class='active'" : ""; ?> href="index2.php">Новости</a> </li> <li> <a <?php echo ($_GET['page'] == 'about') ? "class='active'" : ""; ?> href="index3.php">О сайте</a> </li> </ul> </div> 

Shows an error at startup

Undefined index: page

Tell me, how can I fix it? I don’t consider the JS option yet, with the script the site navigation stops working))))

  • I would advise using filter_input() - ArchDemon

3 answers 3

try this

 <?php $page = isset($_GET['page']) ? $_GET['page'] : 'index'; ?> <div id="nav"> <ul> <li> <a <?php echo ($page == 'index' ? "class='active'" : ""); ?> href="index1.php">Главная</a> </li> <li> <a <?php echo ($page == 'news' ? "class='active'" : ""); ?> href="index2.php">Новости</a> </li> <li> <a <?php echo ($page == 'about' ? "class='active'" : ""); ?> href="index3.php">О сайте</a> </li> </ul> </div> 
  • Thank you very much!!! :)) - Natalia
  • The problem is solved even easier, the error control just turns off)))) - Natalya
  • @ $ _ GET ['page'] ... and do not be wise - Natalya
 <?php $pages = [ 'index' => '', 'news' => '', 'about' => '', ]; if (isset($_GET['page']) && isset($pages[$_GET['page']])) { $idx = $_GET['page']; } else { $idx = 'index'; } $pages[$idx] = 'class="active" '; ?> <div id="nav"> <ul> <li> <a <?=$pages['index']?>href="index1.php">Главная</a> </li> <li> <a <?=$pages['news']?>href="index2.php">Новости</a> </li> <li> <a <?=$pages['about']?>href="index3.php">О сайте</a> </li> </ul> </div> 

    Error Undefined index: page says that the array $ _GET has the wrong index, and the wrong one is here -> !isset($_GET[page]) , i.e. forgot to put quotes. It is necessary so !isset($_GET['page'])

    • Sorry, this is my inattention (in the code that I run, all the quotes are. And the error shows, because initially $ _GET does not exist - Natalia