array_walk vs array_map vs foreach

Jür*_*aul 23 php arrays foreach

我试图比较这三个,但它似乎只有array_map作用.

$input = array( '  hello   ','whsdf                                    ','                              lve you','                              ');
$input2 = array( '  hello   ','whsdf                                    ','                              lve you','                              ');
$input3 = array( '  hello   ','whsdf                                    ','                              lve you','                              ');

$time_start = microtime(true);
$input = array_map('trim',$input);
$time_end = microtime(true);
$time = $time_end - $time_start;

echo "Did array_map in $time seconds<br>";

foreach($input as $in){
    echo "'$in': ".strlen($in)."<br>";
}

////////////////////////////////////////////////

$time_start = microtime(true);
array_walk($input2,'trim');
$time_end = microtime(true);
$time = $time_end - $time_start;

echo "Did array_walk in $time seconds<br>";

foreach($input2 as $in){
    echo "'$in': ".strlen($in)."<br>";
}

////////////////////////////////////////////////


$time_start = microtime(true);
foreach($input3 as $in){
    $in = trim($in);
}
$time_end = microtime(true);
$time = $time_end - $time_start;

echo "Did foreach in $time seconds<br>";

foreach($input3 as $in){
    echo "'$in': ".strlen($in)."<br>";
}
Run Code Online (Sandbox Code Playgroud)

我究竟做错了什么?这是输出:

Did array_map in 0.00018000602722168 seconds
'hello': 5
'whsdf': 5
'lve you': 7
'': 0
Did array_walk in 0.00014209747314453 seconds
' hello ': 10
'whsdf ': 41
' lve you': 37
' ': 30
Did foreach in 0.00012993812561035 seconds
' hello ': 10
'whsdf ': 41
' lve you': 37
' ': 30
Run Code Online (Sandbox Code Playgroud)

它不是修剪array_walkforeach循环.

Sla*_*ava 19

array_walk不看结果函数给出的结果.相反,它传递回调对项目值的引用.所以你的代码需要它

function walk_trim(&$value) {
    $value = trim($value);
}
Run Code Online (Sandbox Code Playgroud)

foreach也不会存储更改的值.将其更改为

foreach ($input3 as &$in) {
    $in = trim($in);
}
Run Code Online (Sandbox Code Playgroud)

了解更多关于引用.

  • 不是吧.但是当你声明它没有引用时,你得到的是一个值,而不是项目本身.如果项目是对象,它将仅在没有引用的情况下工作 顺便说一句,我建议你为你正在测试的方法做多个循环,并在X运行上打印平均值.你的行为并不需要花费太多时间,而且他们采取的微秒也非常近似. (3认同)

Val*_*usk 5

PHP 5.3开始可以使用匿名函数。前任:

$arr = array('1<br/>','<a href="#">2</a>','<p>3</p>','<span>4</span>','<div>5</div>');
array_walk($arr, function(&$arg){
    $arg = strip_tags($arg);
});
var_dump($arr); // 1,2,3,4,5 ;-)
Run Code Online (Sandbox Code Playgroud)

玩得开心。

  • 那是一个看起来丑陋的阵列。 (51认同)
  • @ValentinRusk 我没有听到任何关于所谓的“趋势”的消息。你能详细说明一下吗? (5认同)
  • OOP 并不阻止使用循环...SOLID 与循环无关。事实上,“array_map”是一种函数式编程范例http://en.wikipedia.org/wiki/Map_%28higher-order_function%29 (3认同)