I have a dynamically generated variable that contains the currently selected city by the user. The format of the string is exactly the same as the href in the navigation menu below except without the prefix /city/.
Example:
$user_city = 'london';
$user_city = 'edinburgh';
...
I have the navigation menu below and I want to highlight the currently selected city, that is I want to add a class “active” to the currently selected city.
<ul>
<li class="first"><a href="/city/all">All</a></li>
<li><a href="/city/london">London</a></li>
<li><a href="/city/liverpool">Liverpool</a></li>
<li><a href="/city/edinburgh">Edinburgh</a></li>
<li class="last"><a href="/city/glasgow">Glasgow</a></li>
</ul>
I know I could achieve this by putting each list item into an if statement looking whether $user_city equals the string in the href attribute. But I guess there must be a much smarter way?
Thanks in advance
If you have access to the menu generating function, you can do something like this:
In other words, add a conditional that checks whether the current city stored in
$userCityis the one currently printed on screen and if so add a class to it.Give me a comment if you update your question with your menu generating function. I will show you how to modify it with a conditional then (if you cant figure it from the above now).
If you have to modify the menu after it’s generated and you can be sure the structure is always the same, then you can simply
str_replaceIf you need more difficult string replacements, consider using an HTML parser.