Arrow Functions in PHP 7.4

I was trying out the day-2 problem of the 30-day challenge at leetcode and I came across a situation where a array_map could be used to process each element of the array. Good. Then, I realized that arrow functions were introduced in PHP 7.4 like JavaScript's arrow functions and the entire function can be reduced to one line.

In this case we need to get the sum of all squares of all the digits of a number.

$n = 258;
$digits = str_split($n);
$sum = 0;
foreach ($digits as $digit)
    $sum += ($digit * $digit);
echo $sum.PHP_EOL;

This can be reduced to just

$n = 258;
$sum = array_sum(array_map(fn($a) => $a * $a, str_split($n)));
echo $sum.PHP_EOL;

But leetcode shows a runtime error which probably means that they are not on PHP 7.4.x.

Line 15: PHP Parse error: syntax error, unexpected '=>' (T_DOUBLE_ARROW), expecting ',' or ')' in solution.php

No Comments Yet