Link is not active

-1

I have a menu where when an item is selected, a div appears for that item. But I would like this item to be marked. Trying for PHP, I did this:

<a href="?k=0">Todos</a>
<a href="?k=1">Alunos</a>
<a href="?k=2">Professores</a>
<a href="?k=3">Responsáveis</a>

And in PHP:

switch(isset($_GET['k'])){
    case "0" : $ativo0 = "class=\"uk-active\"";  break;
    case "1" : $ativo1 = "class=\"uk-active\"";  break;
    case "2" : $ativo2 = "class=\"uk-active\""; break;
    case "3" : $ativo3 = "class=\"uk-active\"";  break;
    default : $ativo0 = "class=\"uk-active\"";                                        
} 

No < li > referring to each item:

<li <?php echo $ativo0; ?>>....</li>
<li <?php echo $ativo1; ?>>....</li>
<li <?php echo $ativo2; ?>>....</li>
<li <?php echo $ativo3; ?>>....</li>

Only he leaves only the $ active1

    
asked by anonymous 23.04.2016 / 21:05

1 answer

4

You have a isset left in your code, and the result of isset is always 1 if the variable exists.

See the difference:

switch( $_GET['k'] ){
    case '1' : $ativo1 = 'class="uk-active"'; break;
    case '2' : $ativo2 = 'class="uk-active"'; break;
    case '3' : $ativo3 = 'class="uk-active"'; break;
    default  : $ativo0 = 'class="uk-active"';                                        
}

If you want to use isset , you can do this:

switch( isset($_GET['k']) ? $_GET['k'] : 0 ) {
    case '1' : $ativo1 = 'class="uk-active"'; break;
    case '2' : $ativo2 = 'class="uk-active"'; break;
    case '3' : $ativo3 = 'class="uk-active"'; break;
    default  : $ativo0 = 'class="uk-active"';                                        
}

That is, using a ternary operator we test if K exists, and we choose between K and zero.

Note that I removed case "0" , which is unnecessary because default does the same.

I also removed unnecessary double quotation marks. Double quotes in PHP should only be used when expanding characters such as \n or embedded variables.

Curious, a shorter alternative:

$ativo[isset($_GET['k']) ? $_GET['k'] : 0] = ' class="uk-active"';

<li<?php echo $ativo[0]; ?>>....</li>
<li<?php echo $ativo[1]; ?>>....</li>
<li<?php echo $ativo[2]; ?>>....</li>
<li<?php echo $ativo[3]; ?>>....</li>

In case there is no check for k > 3, but it's just to illustrate (just a min( var ,3) ).

    
23.04.2016 / 22:30