PHP是否有一个相当于Python的名单COM prehension语法? [英] Does PHP have an equivalent to Python's list comprehension syntax?

查看:119
本文介绍了PHP是否有一个相当于Python的名单COM prehension语法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Python有语法甜玉米列表prehensions:

Python has syntactically sweet list comprehensions:

S = [x**2 for x in range(10)]
print S;
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

在PHP我需要做一些循环:

In PHP I would need to do some looping:

$output = array();
$Nums = range(0,9);

foreach ($Nums as $num) 
{
    $out[] = $num*=$num;
}
print_r($out);

获得:



    [0] => 0
    [1] => 1
    [2] => 4
    [3] => 9
    [4] => 16
    [5] => 25
    [6] => 36
    [7] => 49
    [8] => 64
    [9] => 81

Array ( [0] => 0 [1] => 1 [2] => 4 [3] => 9 [4] => 16 [5] => 25 [6] => 36 [7] => 49 [8] => 64 [9] => 81 )

反正是有得到PHP中的类似名单COM prehension语法?反正是有任何的新功能来做到这一点在PHP 5.3?

Is there anyway to get a similar list comprehension syntax in PHP? Is there anyway to do it with any of the new features in PHP 5.3?

谢谢!

推荐答案

也许这样的事情?

$out=array_map(function($x) {return $x*$x;}, range(0, 9))

这将在PHP 5.3+工作,在旧版本的你必须定义回调 array_map 单独

This will work in PHP 5.3+, in an older version you'd have to define the callback for array_map separately

function sq($x) {return $x*$x;}
$out=array_map('sq', range(0, 9));

这篇关于PHP是否有一个相当于Python的名单COM prehension语法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆