Search code examples
phpternary-operatorternary

Ternary Operator with three options


I'm trying to make a ternary operator that says:

  • If the button is == red-btn place red-btn in the a class if it is not check

  • If the button is == white-btn place white-btn in the a class if it is not check

  • If the button is == grey-btn place grey-btn in the a class if it is not check

  • If the button is == red-btn place red-btn etc. etc.

So it checks for one of three options that the user has chosen from my Custom Field Suite dropdown choice that outputs red-btn, white-btn or grey-btn depending on the users selection.

This is my code:

printf("<a class=\"%s\"href=\"%s\">%s</a></div>\n", $colour=="red-btn"?"red-btn": $colour=="white-btn"?"white-btn\": $colour=="grey-btn"?"grey-btn"", $button_link_url, $button_title);

I know this is wrong but need help writing it out correctly.


Solution

  • foreach($buttons as $button){
                            //var_dump($button);
                            $button_title = $button['button_title'];
                            $button_link_url = $button['button_link_url'];
                            $colour = $button['colour'];
    
                            reset($colour);
                            $first_colour = key($colour);
    
                            var_dump($first_colour);
                            printf("<a class='%s' href='%s'>%s</a>\n",
                                ($first_colour=="Red")?"red-btn":(
                                    ($first_colour=="White")?"white-btn":(
                                        ($first_colour=="Grey")?"grey-btn":""
                                    )
                                ),
                                $button_link_url,
                                $button_title
                            );
                        }