首页 > 解决方案 > PHP | Python map() 等价物

问题描述

PHP 有与 Python 的 Map()-Function 等价的功能吗?

如果没有,是否可以自己构建它?

提前致谢!

标签: phppython

解决方案


扩展 vivek_23 的评论。

Python

items = [1, 2, 3, 4, 5]
squared = list(map(lambda x: x**2, items))
print(squared) // [1, 4, 9, 16, 25]

PHP (< 7.4)

$items = [1, 2, 3, 4, 5];
$squared = array_map(function($x) { return $x ** 2; }, $items);
var_dump($squared); // [1, 4, 9, 16, 25]

PHP (7.4 +)

自 7.4 版以来,箭头函数已被引入 PHP。

$items = [1, 2, 3, 4, 5];
$squared = array_map(fn($x) => $x ** 2, $items);
var_dump($squared); // [1, 4, 9, 16, 25]

推荐阅读