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 ad开发者_运维问答d 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
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.
This code uses the alternative syntax for control structures and the 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"' : '' ); ?> ...
The alternative syntax 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; ?>
精彩评论