Working With Switch and If Statements in PhpStorm 2016.1

Posted on by Gary Hockin

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:

$name = 'Luke';

if ( $name == 'Luke' ) {
    $type = 'Jedi';
} elseif ( $name == 'Vader' ) {
    $type = 'Sith';
} elseif ( $name == 'Jar Jar') {
    $type = 'Fool';
} else {
    $type = 'Unknown';

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

Comments below can no longer be edited.

7 Responses to Working With Switch and If Statements in PhpStorm 2016.1

  1. Hendrik Knigge says:

    May 13, 2016

    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 😀

  2. Haroon Mind says:

    May 14, 2016

    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 !

  3. Riho Ellermaa says:

    May 15, 2016

    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…

  4. Michał Opiełka says:

    May 16, 2016

    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.

  5. Constantin Gica says:

    May 17, 2016

    Very nice but please fix this annoying bug:

  6. Math Celebrity says:

    May 20, 2016



Subscribe for updates