开发者

array_key_exists in a foreach

Hi There I am running this code currently,

<?php foreach($search_results as $rslt) : ?>
    <?
    $code = $rslt['code'];
    if(array_key_exists($code, $short_list)) {
        $set = "set";
    }
    ?>
    <div class="row <? echo $set;?>"></div>

What I am trying to achieve is that if the array equals the $rslt['code'] then give the div the class of set otherwise don't the array I checking against looks like this,

    Array
(
    [849650047] => Y开发者_JAVA技巧
    [849652539] => Y
    [849652774] => Y
    [849656557] => Y
    [849652014] => Y
)

However every time I loop all my divs get set with the 'set' class? It should only be where the array_key equals the current $code


Well, they are all set, because you're never initializing the $set variable:

<?php foreach($search_results as $rslt) : ?>
    <?
    $set = '';
    $code = $rslt['code'];
    if(array_key_exists($code, $short_list)) {
        $set = "set";
    }
    ?>
    <div class="row <? echo $set;?>"></div>

Also, just use isset() instead of array_key_exists (it's more efficient, and less wordy):

    if(isset($short_list[$code])) {
        $set = "set";
    }


just add unset($set); at end of your loop. Or you can do something like...

<?php foreach($search_results as $rslt) : ?>
    <div class="row <? print array_key_exists($rslt['code'], $short_list)? 'set':''; ?>"></div>
<?php endforeach; ?>


Avoid the alternate control structure syntax in PHP. It's ugly and makes your code more difficult to maintain in the long run. Also try to avoid excessive context switching with <?php ?>; it makes your logic needlessly difficult to follow.

<?php

foreach ($search_results as $result) {
  $set = isset($short_list[$result['code']]) ? ' set' : '';
  echo "<div class=\"row$set\"></div>";
}

Note that isset() will return false if the key exists in the array, but its value is null. Something to watch out for if you want the "set" class applied even if the value of $short_list[$result['code']] is null.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜