是否可以在 php 中不循环地更改数组的所有值?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12691221/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Is it possible to change all values of an array without a loop in php?
提问by Benjamin Crouzier
I have the following array in php:
我在 php 中有以下数组:
$a = $array(0, 4, 5, 7);
I would like to increment all the values without writing a loop (for, foreach...)
我想在不编写循环的情况下增加所有值(for,foreach ...)
// increment all values
// $a is now array(1, 5, 6, 8)
Is it possible in php ?
在 php 中可以吗?
And by extention, is it possible to call a function on each element and replace that element by the return value of the function ?
通过扩展,是否可以在每个元素上调用一个函数并用函数的返回值替换该元素?
For example:
例如:
$a = doubleValues($a); // array(0, 8, 10, 14)
回答by Michael Berkowski
This is a job for array_map()(which will loop internally):
这是一项工作array_map()(将在内部循环):
$a = array(0, 4, 5, 7);
// PHP 5.3+ anonmymous function.
$output = array_map(function($val) { return $val+1; }, $a);
print_r($output);
Array
(
? ? [0] => 1
? ? [1] => 5
? ? [2] => 6
? ? [3] => 8
)
Edit by OP:
OP编辑:
function doubleValues($a) {
return array_map(function($val) { return $val * 2; }, $a);
}
回答by Rubberducker
Yeah this is possible using the PHP function array_map()as mentioned in the other answers.This solutions are completely right und useful. But you should consider, that a simple foreach loop will be faster and less memory intense. Furthermore it grants a better readability for other programmers and users. Nearly everyone knows, what a foreach loop is doing and how it works, but most PHP users are not common with the array_map() function.
是的,这可以使用其他答案中提到的 PHP 函数array_map() 实现。这个解决方案是完全正确和有用的。但是您应该考虑,一个简单的 foreach 循环会更快,内存更少。此外,它为其他程序员和用户提供了更好的可读性。几乎每个人都知道 foreach 循环在做什么以及它是如何工作的,但大多数 PHP 用户对 array_map() 函数并不常见。

