In PHP, I have an array:
$a = array(10, 15, 20, 25, 30);
I want to add 5% to each element of the array $a, so that it looks like this:
$a = array(10.5, 15.75, 21, 26.25, 31.5);
I do not want to use foreach.
In PHP, I have an array:
$a = array(10, 15, 20, 25, 30);
I want to add 5% to each element of the array $a, so that it looks like this:
$a = array(10.5, 15.75, 21, 26.25, 31.5);
I do not want to use foreach.
Use array_map():
$a = array(10, 15, 20, 25, 30);
$a = array_map(function($value) { return $value * 1.05; }, $a);
Gives: array(10.5, 15.75, 21, 26.25, 31.5);
Try this
<?php
$a = array(10, 15, 20, 25, 30);;
$output = array_map(function($val) { return $val + ($val*5/100); }, $a);
print_r($output);
?>
Output :-
Array
(
[0] => 10.5
[1] => 15.75
[2] => 21
[3] => 26.25
[4] => 31.5
)
The array_map function should be the solution you are looking for (documentation here).
I guess you'll have to create a function like this :
function fivePercent($n)
{
return($n * 1.05);
}
And use array_map to call it on each number in your array :
$b = array_map("fivePercent", $a);
edit : Working code here.
edit 2 : According to the answer here, it is faster to use foreach, but since you asked not to use it, calling a named function is much faster than writing the function in the array_map call. Anyway, it doesn't matter with small arrays, just consider this when you have a lot of numbers to deal with.
Here is your custom function,
$arr = array_map(function($i){
return $i+($i*0.05);
}, $arr);
print_r($arr);
Here is working code.
array_map — Applies the callback to the elements of the given arrays
Of course, a language construct can be used to loop the array and an as proven by several other answers array_map() will do the job, but when you want to apply a user function to every element in an array, that is what array_walk() is designed for. The values are "modified by reference" as they are iterated instead of creating a whole new array then overwriting the old data with the new returned array.
Use the Mulitplication Assignment Operator to apply the 5% boost to each value encountered.
Code: (Demo)
function fivePercentIncrease(&$value) {
$value *= 1.05;
}
$a = [10, 15, 20, 25, 30];
array_walk($a, 'fivePercentIncrease');
var_export($a);
Or via an anonymous function: (Demo)
$a = [10, 15, 20, 25, 30];
array_walk($a, function(&$value) { $value *= 1.05; });
var_export($a);
Or via an anonymous function using PHP7.4's arrow function syntax: (Demo)
$a = [10, 15, 20, 25, 30];
array_walk($a, fn(&$value) => $value *= 1.05);
var_export($a);