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)
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.
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.
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.
The PHP foreach Loop The foreach loop works only on arrays, and is used to loop through each key/value pair in an array.
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With