How to make a language switcher menu in PHP

this snippet will work if you have a structure like this

(English pages)




(Spanish pages)




This is the code you can put in a menu as a list item. It would work nicely in a wordpress website.

<? if (substr($_SERVER[“REQUEST_URI”],1,2) == “es”) { ?>
<li><a href=”/<? echo substr($_SERVER[“REQUEST_URI”],4); ?>”>In English</a></li>
<? } else { ?>
<li><a href=”/es<? echo $_SERVER[“REQUEST_URI”]; ?>”>En espaƱol</a></li>
<? } ?>