views:

32

answers:

3

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
    [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

+4  A: 

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";
    }
ircmaxell
its not never initializing, its not resetting the value of $set while iterating on next member
KoolKabin
Well, it's never initializing it either. Which will at best throw a notice, or at worse open yourself up to a register_globals attack. ALWAYS initialize all variables. Especially if you're setting them in a conditional, and using them outside of the conditional...
ircmaxell
A: 

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; ?>
Tarentrulle
A: 

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.

meagar