Link is not active

Asked

Viewed 54 times

-1

I have a menu from which when an item is selected, a div for that item appears. However, I would like that item to be marked. Trying for PHP, I did it this way:

<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 > for each item:

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

Only that it leaves marked only the $active1

  • put a div inside the a

1 answer

4


Has 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 the isset, can do so:

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 choose between K and zero.

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

I also removed unnecessary double quotes. Double quotes in PHP should only be used when you have character expansion like \n or embedded variables.

Of curiosity, 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 this case there is no check of k > 3, but it is only to illustrate (one would be enough min( var ,3)).

  • 1

    Perfect Bacco.... was the same isset() ... thank you!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.