0

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.

1

2 Answers 2

4

Try

<?
$cats = array(1,3,4,8);
foreach($cats as $value) {
 if($value != "") {
 ?>
   <div>Entries for <?= $value; ?></div>
 <?
 }
}
?>
Sign up to request clarification or add additional context in comments.

Comments

2

Use an array like this:

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

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

}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.