liz
liz

Reputation: 483

trying to write a proper if statement in php

i am having a hard time wrapping my head around how to do this... i have a select menu i want to display as default and a different one(s) if certain items appear in a shopping cart.

so say i sell dogs and cars. in the cart i have selected one of each. i want one select menu to appear if there are ever any cars in the cart. but if there are ever any dogs in the cart or cats for that matter i want a different select with different options to appear. so car_select would be the default if anything is in the cart...(i sell a lot of stuff) but if a dog appears in the cart then dog_select would replace it.

the way it is written now. the default is the last thing and that is what shows. (see my comments)

so the code:

<?php
foreach($this->rows as $i => $row){

if (strstr('dogs',$row->dates)) {
$mydates = 'dogs';
} else {$mydates='default';}


//echo $row->dates; this spits out the correct values dogcar


}
//echo $mydates; with a dog and a car in the cart this returns default
//below functions i believe but i think the above is faulty 
?>
<?php 
if ($mydates =='dogs'){
//do something here;} else {

    $type = $this->type;
    foreach($this->extraFields[$type] as $fieldName => $oneExtraField) {
     if ($fieldName != 'pickupdate-rosh'){; ?>
        <tr class="hikashop_checkout_<?php echo $fieldName;?>_line">
            <td class="key">
                <?php echo $this->fieldsClass->getFieldName($oneExtraField);?>
            </td>
            <td>
                <?php 

                        echo $this->fieldsClass->display($oneExtraField,$this->$type->$fieldName,'data['.$type.']['.$fieldName.']'); 
                ?>
            </td>
        </tr>
<?php } ?>
    <?php } ?>
<?php } ?>

i would like to always return car_select unless the presence of dogs or cats etc in the cart. {edit: i just realized that is not the correct function to use to look for a string.}

Upvotes: 0

Views: 104

Answers (1)

Jared Farrish
Jared Farrish

Reputation: 49208

It looks like you're setting $mydates, then overriding it (potentially). This is because you're setting one variable to one result for all iterations of your foreach loop, and the last iteration will be what the final variable value will be.

So set $mydates to a default and then change it if the condition is right.

$mydates='default';
foreach($this->rows as $i => $row){
    if (strstr('dogs',$row->dates)) {
        $mydates = 'dogs';
    }
    //echo $row->dates; this spits out the correct values dogcar
}

Upvotes: 2

Related Questions