Arrow Functions in PHP 7.4
Among the few features that got added to the latest released version of PHP 7, the arrow function feature seems to be amazing to me since it has been in JS ES6. So I decided to talk about it using some common Higher Order Functions we already know — array_map() and array_filter.
array_filter() iterates over each value in the array
passing them to the callback
function. If the callback
function returns TRUE
, the current value from array
is returned into the result array. Array keys are preserved.
Let us take a look on how this is used in the previous versions of PHP before PHP 7.4. You would see the need to leverage PHP 7.4 to make things lot easier and cleaner. Yes! Cleaner
Let’s us get to it, now take a look at the code below:

This is the regular way we write the php and use array_filter() function before PHP 7.4
Now let’s look at what PHP 7.4 brings to the table with same example of code above:

Did you notice how 3 lines of code got reduced to 1 in line 4–6 and line 4 of the two examples above respectively and same result is being produced?
Did you also noticed the weird fn keyword in the second example? Well, it means function. And yes there is an implicit return with the arrow function.
Now let us take a look at another common Higher Order Function
array_map() returns an array containing the results of applying the callback
function to the corresponding index of array1
(and ...
if more arrays are provided) used as arguments for the callback. The number of parameters that the callback
function accepts should match the number of arrays passed to array_map().
An example of this and how it can be used previous versions PHP before 7.4:

PHP 7.4 makes writing the same piece of code cleaner and faster with arrow function feature.
Let’s take a look:

Isn’t this much cleaner and faster?