Working With Switch and If Statements in PhpStorm 2016.1

We’re all told that great developers refactor often (I looked for a quote on who said that, but couldn’t find anyone, so now it’s mine). Refactoring can be a tedious job, but PhpStorm’s intentions can help you break away from the tedium and get the task done quicker.

New in PhpStorm 2016.1 are a couple of intentions specifically designed to make refactoring between switch and if statements as painless as possible.  Let’s consider this code:

This code is not the nicest-looking in the world; arguably it would be better suited to a switch statement. Thankfully, in the latest version of PhpStorm flipping between switch and if is easy thanks to the new intention.

Here you can see that we use the Quick-fix keyboard shortcut (Alt + Enter on Windows/Linux, Cmd + Enter on Mac) to see what intentions we can invoke at the location of the caret. We pick “Replace ‘if’ with ‘switch'” and voila, our complex if statement is replaced with a nice, readable switch statement.

We can also convert theswitch back to an if/else by invoking the opposite intention in exactly the same way.

Give it a try and let us know what you think. We’re also interested to hear what other refactoring intentions you’d like to see in the future.

– Gary and the PhpStorm Team

The Drive to Develop

About Gary Hockin

Gary Hockin has been creating code to power web applications for 15 years, the last three of them at an extraordinary level. He is handsome, talented, funny and articulate, and also extremely modest. Gary is a valued contributor to Zend Framework 2 and is a member of the community review team. He's married and has two wonderful children, and when he's not coding, writing about code, speaking about code or reading about code, he can usually be found in the pub playing pool.
This entry was posted in Cool Feature and tagged , , . Bookmark the permalink.
  • Hendrik Knigge

    Wow, nice one. All these little things together make a great difference.

    Im just waiting for that day phpstorm will fix my dumb nested if statements 😀

  • Haroon Mind

    hahaha your first quote I Liked the most ,
    Some time I thought that I am the only one who have patent stamp
    well geniuszem is not that who find first is about when you get that even sugar is sweet !

  • Riho Ellermaa

    But what I would really like for my old legacy projects is to replace all snake_case variables with camelCase in a file in one go. Not going through every local one by one…

  • Michał Opiełka

    Looks fine, but I think it’s better to store values like these in an associative array, then preset a variable to default value and if array key exists, then change it. Or just use one if/else for it.

  • Constantin Gica

    Very nice but please fix this annoying bug:

  • Math Celebrity