Refactor your code to functional style with PhpStorm 2018.1

How many times you wrote code like this to achieve a simple purpose?

Mapping values of an array:

Filtering:

Or reducing an array to some value:

The above code samples involve the imperative programming style, which is familiar to everybody. It has a certain flaw: we have to parse the code in our head and go through negligible but required details to understand it.

To solve this issue, PHP suggests relying on the built-in functions: array_map, array_filter, array_reduce, etc. These functions can improve readability and emphasize the intent of your code. Unfortunately, it’s not always clear when and how to apply them to the existing code, since in some cases details can be crucial.

To help you with the task, we are going to introduce automatic ways of transforming imperative code to functional equivalents via the corresponding inspections and quick fixes. Since there can be a lot of tricky cases and possible transformations, we’ve decided to start with the simplest case of the foreach to array_map transformation inspection and quick fix.

In PhpStorm 2018.1 EAP, you can find the new Loop can be converted to ‘array_map’ call inspection under Settings | Editor | Inspections | PHP | Code Style and apply the corresponding quick fix as usual, by pressing Alt + Enter.

array_map_3

Should you reconsider, the ‘array_map’ call can be converted to loop inspection and quick fix, which do exactly the opposite, are provided, too.

We’re going to add more transformations and cover more cases in the future.

What do you think about functional programming in PHP? What types of transformation do you find the most useful? Give us your opinions in the comments or tweet @phpstorm!

Your JetBrains PhpStorm Team
The Drive to Develop

About Kirill Smelov

PhpStorm developer
This entry was posted in Cool Feature and tagged , . Bookmark the permalink.
  • http://matthewhailwood.co.nz/ Matthew Hailwood

    This is a great feature, I’m often forgetting the name of one of the array functions even though I find them far easier to understand, so a quick intention to switch between the imperative and functional versions is great!

  • kyriakos

    I understand the readability point but aren’t these functions much slower?

  • Константин

    For what wrap with closure? Why not just array_map('func', $items) ?