是否可以更改数组的所有值而无需在php中循环? [英] Is it possible to change all values of an array without a loop in php?

查看:64
本文介绍了是否可以更改数组的所有值而无需在php中循环?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在php中有以下数组:

I have the following array in php:

$a = $array(0, 4, 5, 7);

我想在不编写循环的情况下增加所有值(对于foreach ...)

I would like to increment all the values without writing a loop (for, foreach...)

// increment all values
// $a is now array(1, 5, 6, 8)

是否可以在php中使用?

Is it possible in 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 ?

例如:

$a = doubleValues($a); // array(0, 8, 10, 14)

推荐答案

这是的工作 array_map() (将在内部循环):

This is a job for array_map() (which will loop internally):

$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
)

由OP

function doubleValues($a) {
  return array_map(function($val) { return $val * 2; }, $a);
}

这篇关于是否可以更改数组的所有值而无需在php中循环?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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