• Resolved cwebb41

    (@cwebb41)


    Trying to get different images to come up under two specific conditions. For example:

    <?php
    if($item->product_id == ’12’)
    {
    echo ‘<img src=”ticket6.jpg”>’;
    }

    elseif($item->product_id == ‘2’ and $item->quantity == ‘2’) {
    echo ‘<img src=”ticket8.jpg”>’;
    }

    elseif($item->product_id == ‘2’ and $item->quantity == ‘3’) {
    echo ‘<img src=”ticket9.jpg”>’;
    }
    ?>

Viewing 4 replies - 1 through 4 (of 4 total)
  • Moderator bcworkz

    (@bcworkz)

    Other than the fact there are 3 conditions, not 2, you seem to understand what to do. What’s the problem? In what way is this not doing what you want?

    Thread Starter cwebb41

    (@cwebb41)

    The two elseif conditions are posting the same image (ticket8.jpg)……would like it ouput a different image when the quantity changes…….is there a way to make this work “if only” when two conditions are met to ouput different images?

    Moderator bcworkz

    (@bcworkz)

    Your script will work the way you want based on what I see. There may be some other flaw in your code related to when the quantity changes. You should be getting ticket9.jpg if the quantity is indeed 3. Try adding this line before the if() block: echo '<pre>'; var_dump($item); echo '</pre>'; so you can see what values are actually being used.

    For the sake of discussion, there are other approaches for this type of scenario which could yield code that is easier to “read”. You can nest if() blocks like so:

    if($item->product_id == '2'){
       if($item->quantity == '2') echo '<img src="ticket8.jpg">';
       elseif($item->quantity == '3') echo '<img src="ticket9.jpg">';
       else echo '<img src="oops.jpg">';
    }

    Note that it’s often a good idea to provide a terminal condition (the oops.jpg I added) to trap any situation where the current conditions fail to match anything expected.

    If any particular condition has more than a couple possible values, it’s probably clearer to use a switch/case structure. This too can be nested or combined with if/else structures in any way that makes sense.

    Thread Starter cwebb41

    (@cwebb41)

    Beautiful…….worked like a charm! Thanks for your help.

Viewing 4 replies - 1 through 4 (of 4 total)
  • The topic ‘Combing Two If Conditions’ is closed to new replies.