html - PHP multiply each value in the array by an additional argument -
i trying create php function multiplies values/content of array given argument.
modify function can pass additional argument function. function should multiply each value in array additional argument (call additional argument 'factor' inside function). example $a = array(2,4,10,16). when say
$b = multiply($a, 5); var_dump($b); should dump b contains [10, 20, 50, 80 ]
here's code far:
$a = array(2, 4, 10, 16); function multiply($array, $factor){ foreach ($array $key => $value) { echo $value = $value * $factor; } } $b = multiply($a, 6); var_dump($b);
any idea? thanks!
your function not right, has return array , not echo values.
function multiply($array, $factor) { foreach ($array $key => $value) { $array[$key]=$value*$factor; } return $array; }
rest fine.
you can array_map
$a = array(2, 4, 10, 16); print_r(array_map(function($number){return $number * 6;}, $a));
Comments
Post a Comment