1

Is there a way through the context menus to refactor a ternary assignment into one that is done with an if-else block?

So, for example you'd have something like this:

$a = ($b > -32)? "up" : "down";

You'd then apply this transformation, and PHPStorm would magically change it into:

if ($b > -32) {
    $a = "up";
} else {
    $a = "down";
}

Seems like a really common and easily automated operation, so it must be automated somewhere in this labyrinth of menus.

2
  • 1
    "Seems like a really common and easily automated operation" common? Hmm .. usually doing other way around... In any case: there is an Intention to perform such conversion in both directions. Problem is: batch fixing can only be applied to problematic places (i.e. a place to which specific Inspection is pointing). As we all know -- both ways are actually good code... so I do not see how such intention can be applied in a batch. But sure -- "Code | Inspect code" and see if IDE will pick up anything there (any "fixes" to specific issue will be listed under "light bulb" icons).
    – LazyOne
    Commented Nov 3, 2014 at 19:21
  • I wanted this by use case case was deminifying javascript code that had horrible nested ternery like so video ? video.getPaused() ? video.play() : (video.pause(), d.a.set("pauseCount", d.a.get("pauseCount") + 1)) : (ne(".PlayerControls--button-control-row").children().eq(0).trigger("click"). But I guess this is only because someone else already destroyed the intent of the code.
    – Att Righ
    Commented Aug 1, 2022 at 21:39

2 Answers 2

5

PHPStorm 8 can do it with Alt-Enter shortcut. Put your cursor at the ? operator and key in Alt+Enter.

3

As I am using PHPStorm 10 right now when I was trying to turn a simple if and else into a ternary operator I could select my code as I have shown in this little screen shot below:

enter image description here

Then I clicked on that little bulb or you can use alt + return to choose Simplify If and if my code could be simplified with ternary operator then it will become one as I have shown in the screenshot below otherwise the IDE will not show you any output message:

enter image description here

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.