phpphp-generators

Easier menu generation depended on session


I am making a menu for website language and it works but i think the way i am doing it is not the best way in case i add more languages in future. Maybe someone can show a better example. Here is a piece of what i've got.

if(isSet($_SESSION['lang'])) {
    $lang = $_SESSION['lang'];
    if ($lang == "en") {
        echo '<li class="">EN 
              <ul>
              <li class="submenu">RU</li>
              <li class="submenu">ES</li>
              <li class="submenu">GR</li>
              <li class="submenu">DE</li>
              </ul>
              </li>';
    }
    if ($lang == "de") {
        echo '<li class="">DE 
              <ul>
              <li class="submenu">RU</li>
              <li class="submenu">ES</li>
              <li class="submenu">GR</li>
              <li class="submenu">EN</li>
              </ul>
              </li>';
    }
    // and so on for every language.. 
}

Probably would be better doing some array and than foreach function, but i have no idea how to do that x,x way too confusing


Solution

  • If you want an array, it's possible to create a function, this function will get the language as parameter and display the options according to it :

    <?php
    
    function display ( $lang )
    { $arr = array( "en" => array( "RU","ES","GR","DE" ),
                    "de" => array( "RU","ES","GR","DE" )
                  );
      echo '<li class="">' .
           '<ul>';
      foreach ( $arr[ $lang ] as $item ) // DISPLAY THE OPTIONS.
        echo '<li class="submenu">' . $item . '</li>';
      echo '</ul>
            </li>';
    }
    
    display( "en" ); // DISPLAY OPTIONS FOR "EN".
    display( "de" ); // DISPLAY OPTIONS FOR "DE".
    
    ?>
    

    In the future, you may add more languages to the array.

    To test it, copy-paste previous code in a file, save it as PHP and open it in your browser.