Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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)
like image 501
Benjamin Crouzier Avatar asked Oct 02 '12 13:10

Benjamin Crouzier


People also ask

How do you change all values in an array?

To change the value of all elements in an array:Use the forEach() method to iterate over the array. The method takes a function that gets invoked with the array element, its index and the array itself. Use the index of the current iteration to change the corresponding array element.

Can arrays values be changed?

so yes the value of the int IN the array is changed from operations in the method. In short methods don't change the external value of primitives (int,float,double,long,char) with the operations in the method, you have to return the resulting value of those operations to the caller if you wish to obtain it.

How can I replace one element in an array in PHP?

The array_replace() function replaces the values of the first array with the values from following arrays. Tip: You can assign one array to the function, or as many as you like. If a key from array1 exists in array2, values from array1 will be replaced by the values from array2.

Which loop works only on arrays in PHP?

The PHP foreach Loop The foreach loop works only on arrays, and is used to loop through each key/value pair in an array.


1 Answers

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);
}
like image 191
Michael Berkowski Avatar answered Sep 22 '22 12:09

Michael Berkowski