user966585
user966585

Reputation: 850

Using PHP loop to reduce code

I have few drop down boxes from where I can get an id of a category. For example, from drop down box 1, i get $cat1, from box 2 i get $cat2 and so on.

Then I want to get the entries from db for each of the cat id. Currently I am repeating same code for each of the variable, like:

<?
$cat1 = 1;
$cat2 = 3;
$cat3 = 4;
$cat4 = 8;

<? if ($var1 != ""){ ?> 
    <div>
        Entries for <? echo $var1; ?>           
        ..
    </div>
<? } ?>

<? if ($var2 != ""){ ?> 
    <div>
        Entries for <? echo $var2; ?>
        ..
    </div>
<? } ?>

<? if ($var3 != ""){ ?> 
    <div>
        Entries for <? echo $var3; ?>
        ..
    </div>
<? } ?>

I'd like to know if I can use a loop and avoid writing code for each variable.

Upvotes: 0

Views: 145

Answers (2)

nooga
nooga

Reputation: 570

Try

<?
$cats = array(1,3,4,8);
foreach($cats as $value) {
 if($value != "") {
 ?>
   <div>Entries for <?= $value; ?></div>
 <?
 }
}
?>

Upvotes: 4

Rene Pot
Rene Pot

Reputation: 24815

Use an array like this:

$cat[1] = 'bla';
$cat[2] = 'Bla2';

    foreach ($cat as $c){
    if ($c != ""){ 
    echo '
        <div>
            Entries for '. $c.'
            ..
        </div>';
    }

}

Upvotes: 2

Related Questions