开发者

php variable not returning what is expected

I have an unordered list that's being generated from a database. Depending on the value of one of the returned fields, the li tag's class should be set to differe开发者_C百科nt values. Unfortunately they're all returning "inactive". I know this must be something simple, but I've been staring at it for hours and am just not seeing it.

Here's the code:

<ul class="tabs">
   <? foreach ($tracks AS $track) {
    $active = (strtolower($track->shortname === 'dpp')) ? ' class="active"' : 'class="inactive"';
    echo "<p>".strtolower($track->shortname). " is ".$active."</p>"; ?>
    <li <?= $active; ?>><a href="#<?= strtolower($track->shortname); ?>"><?= $track->name; ?></a></li>
   <? } ?>
</ul>

Here's what is actually getting printed:

<ul class="tabs"> 
    <p>dpp is class="inactive"</p>  <li class="inactive"><a href="#dpp">Digital Path to Purchase</a></li> 
    <p>cre is class="inactive"</p>  <li class="inactive"><a href="#cre">Fueling Creativity</a></li> 
</ul> 

It's obvious that the first one is returning $track-shortname of dpp, so why is the $active variable not getting set to "class=active"?


You've made an error in the expression where you check the shortname:

$active = (strtolower($track->shortname === 'dpp')) ? ' class="active"' : 'class="inactive"';
                     ^                           ^

You most certainly only want to put it around $track->shortname:

$active = (strtolower($track->shortname) === 'dpp') ? ' class="active"' : 'class="inactive"';
                     ^                 ^

Otherwise you tried to lowercase a boolean value which is either true or false but in your case it looks to always be false, hence the inactive CSS class.

BTW, you can spare another pair:

$active = strtolower($track->shortname) === 'dpp' ? ' class="active"' : 'class="inactive"';
         ^                                       ^


The code (strtolower($track->shortname === 'dpp')) looks wrong. Your putting the strtolower around the comparison, and you probably just want it around the $track->shortname.


One of your close parentheses is in the wrong place.

Change:

$active = (strtolower($track->shortname === 'dpp')) ? ' class="active"' : 'class="inactive"';

To:

$active = (strtolower($track->shortname) === 'dpp') ? ' class="active"' : 'class="inactive"';

With the parenthesis in the wrong place, $track->shortname is compared to dpp before any lower-case conversion. Then the result of that comparison (boolean) is passed to strtolower. That results in strtolower simply returning a string representation of that which results in the ternary comparison evaluating to false.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜