¿Cómo agrego una identificación a un elemento del menú si se cumple una condición?

I need to add an ID to the Li if a condition is met. I did something like this previously:

if ($school == $array[1])
{ 
echo " id=\"current\"";
}

It basically should add the id "current" if $school equals $array[1] but I'm not sure how to do it since it's php inside html inside php and I don't have much experience with PHP so I'm kinda lost.

This is where I want to add it:

   <?php
    if($array[1] != "")  { echo '<li class="menu-item menu-item-type-post_type menu-item-10">' .
    '<a href="http://chusmix.com/?s=' . $city . '++++' . str_replace(" ", "+", $array[1]) . '">' .
    '' . $array[1] . '' .
    '</a>' .
    '</li>';
    }
    ?>

Thanks for any help, info etc

preguntado el 09 de enero de 11 a las 00:01

2 Respuestas

Your code in a nice way:

<?php if($array[1] != ""): ?>
    <li id="<?php echo ($school == $array[1] ? 'current' : '' ); ?>" class="menu-item menu-item-type-post_type menu-item-10">
        <a href="http://chusmix.com/?s=<?php echo $city . '++++' . str_replace(' ', '+', $array[1]); ?>">
            <?php echo $array[1]; ?>
        </a>
    </li>
<?php endif; ?>

But I would reduce the number classes (or at least reduce the length, menu-item-type-post_type seems to be unpractical if it is not auto-generated) and add a class current instead of an ID.

Este código usa el sintaxis alternativa para estructuras de control y el ternary opertor.

p.s: I'm not 100% sure how an empty ID is handled, by I think it is just ignored. If it causes problems, you can also do

<li <?php echo ($school == $array[1] ? 'id="current"' : '' ); ?> ...

Respondido el 09 de enero de 11 a las 04:01

La sintaxis alternativa is your friend. It helps you minimize echos.

<?php if($array[1] != ""): ?>
    <li class="menu-item menu-item-type-post_type menu-item-10"<?php if ($school == $array[1]): ?>id="current"<?php endif; ?>>
    <a href="http://chusmix.com/?s=<?php echo $city . '++++' . str_replace(" ", "+", $array[1]); ?>"><?php echo $array[1]; ?></a>
    </li>
<?php endif; ?>

Respondido el 09 de enero de 11 a las 04:01

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.