Is it possible to change all values of an array without a loop in php?

馋奶兔 提交于 2020-12-28 07:08:30

问题


I have the following array in php:

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

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)

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 ?

For example:

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

回答1:


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
)

Edit by OP:

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



回答2:


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.




回答3:


$arr = array(0, 4, 5, 7);
function val($val) { return $val+1; }
$arr = array_map( 'val' , $arr );
print_r( $arr );

See it here



来源:https://stackoverflow.com/questions/12691221/is-it-possible-to-change-all-values-of-an-array-without-a-loop-in-php

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!