PHP multiply each value in an array by an optional argument
I was trying to create a PHP function that multiplies the values ββ/ contents of an array by a given argument.
Modify this function so you can pass an additional argument to this function. The function should multiply each value in the array by this extra argument (let's call this extra argument the "factor" inside the function). For example, let's say $ A = array (2,4,10,16). When you say
$B = multiply($A, 5);
var_dump($B);
this should dump B which contains [10, 20, 50, 80 ]
Here's my code:
$A = array(2, 4, 10, 16);
function multiply($array, $factor){
foreach ($array as $key => $value) {
echo $value = $value * $factor;
}
}
$B = multiply($A, 6);
var_dump($B);
Any idea? Thank!
+3
source to share
4 answers
Your function is wrong, it should return this array and not echo some values.
function multiply($array, $factor)
{
foreach ($array as $key => $value)
{
$array[$key]=$value*$factor;
}
return $array;
}
Rest is fine.
You can even do this with array_map
$A = array(2, 4, 10, 16);
print_r(array_map(function($number){return $number * 6;}, $A));
+5
source to share