0

is there any way to show 3 conditions of a variable and not just 2?

With this

<?php echo $squar['product'] = 0 ? ' soldout ' : $squar['product'];?>

I can display conditionA 'soldout' and conditionB f.e. '123'.
How to show a conditionC '> 100' if there are more than 100 'product' in stock?
Tried a lot and searched for a solution, but found nothing. Thank you.

george
  • 15
  • 1

2 Answers2

1

Using elseif condition as per docs

<?php

    // example value

    $squar['product'] =50;


    if ($squar['product'] ==0){

      echo "soldout";

    } elseif ($squar['product']>0 & $squar['product']<=100){

      echo $squar['product'];

    } elseif($squar['product']>100){

      echo 'plus 100';

    }

    ?>

Code tested at 3v4l

Lew Perren
  • 1,209
  • 1
  • 10
  • 14
  • I´m also not such a friend of nested solutions, but a ternary comparison is just a line of code. Have to fill a few hundred table fields with that code (for getting a fast product overvier). – george Sep 19 '17 at 10:37
  • 1
    Will test @Poiz nested ternary comparison first. Otherwise I have to use if..elseif..else solution as recommended. Thank you for help! – george Sep 19 '17 at 10:48
  • @george personally I would use the if..elseif code, but put it in a function. Then the code is encapsulated, you can forget it knowing it works and you will have a very short code block to call the function. Also, refactoring will become easy, the function could have parameter(s) that are easy to change. Something like ProdStock($plusThreshold). So you can do ProdStock(100) for example. – Lew Perren Sep 19 '17 at 11:26
  • 1
    @BusinessPlanQuickBuilder **Same Love back to You!!!!**...Thanks Mate... ...your generous heart is enviable: ☝️❤️ – Poiz Sep 19 '17 at 12:07
  • @Poiz - Thanks :-) – Lew Perren Sep 19 '17 at 12:21
1

As @BusinessPlanQuickBuilder pointed out, A simple if...elseif...else would do the Trick. However, if your intent is to stick to Ternary Comparison; it is also very much possible to nest them like so:

<?php echo  (  $squar['product'] == 0)      ? ' soldout '   :
            ( ($squar['product'] > 100)     ? '> 100'       :  $squar['product']);
?>

This is basically saying the same thing as @BusinessPlanQuickBuilder. You can think of @BusinessPlanQuickBuilder's approach as speaking Inglés and this approach as spitting Anglais.... Both are saying the same thing - only in different ways... So you can choose whether to join the Spanish Team or Rock with that French Club... Honestly, in this context, one would not be in Error to choose Inglés because it is much more human-readable plus Spanish is so much Fun...

Cheers & Good-Luck, Mate ✌️☝️

Poiz
  • 7,611
  • 2
  • 15
  • 17
  • Nice solution, certainly less code. I just find Inglés more readable :-) – Lew Perren Sep 19 '17 at 11:38
  • 1
    @BusinessPlanQuickBuilder **Same Love back to You!!!!**...Thanks Mate... ...your generous heart is enviable: ☝️❤️ – Poiz Sep 19 '17 at 12:09