Salman
Salman

Reputation: 1024

Ternary ignores first condition

Why is my ternary ignoring the first condition ($order->status === "prepairing") ?

It always skips the first condition when checking the order status and immediately goes toward the second (and always see's it as true)

$messageMiddle = (  ($order->status === "prepairing") ? " your prder is being prepared. Make your way towards the store." 
                  : ($order->status === "complete")   ?' your order is done! Please show your order-code at the store.' 
                  : ' thank you for ordering ');

Upvotes: 0

Views: 74

Answers (2)

KIKO Software
KIKO Software

Reputation: 16688

A better way to react to the status of an order would be a switch statement. Like this:

switch ($order->status) {
    case "preparing" : $messageMiddle = " your order is being prepared. Make your way towards the store.";
                       break;
    case "complete"  : $messageMiddle = " your order is done! Please show your order-code at the store.";
                       break;
    default          : $messageMiddle = " thank you for ordering ";
                       break;
}

It is easy to see how you can extend this to react to other status words.

Note that I changed `"prepairing" to "preparing".

One of the things programmers strive for is succinct code. However, shorter code is not always better code. It might be less readable and more difficult to maintain and extend.

Upvotes: 1

Syed Ahmed Jamil
Syed Ahmed Jamil

Reputation: 2126

You need to group every next expression in parenthesis as follows. You forgot to enclose the second ternary expression in parentheses.

$messageMiddle = ($order->status === "prepairing") ? " your order is being prepared. Make your way towards the store." : 
                 (($order->status === "complete")  ? ' your order is done! Please show your order-code at the store.'  : ' thank you for ordering ');

But you should avoid this approach anyways.

Upvotes: 1

Related Questions