WordPress.org

Ready to get started?Download WordPress

Forums

[resolved] Combing Two If Conditions (5 posts)

  1. cwebb41
    Member
    Posted 8 months ago #

    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">';
    }
    ?>

  2. bcworkz
    Member
    Posted 8 months ago #

    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?

  3. cwebb41
    Member
    Posted 8 months ago #

    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?

  4. bcworkz
    Member
    Posted 8 months ago #

    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.

  5. cwebb41
    Member
    Posted 8 months ago #

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

Reply

You must log in to post.

About this Topic