Reputation: 295
I want to know if there is a map function or similar to use with array values? Say I have the following array..
$nums = array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
I want to multiply these values by 5, changing the array values where my expected output would be.
Array
(
[0] => 5
[1] => 10
[2] => 15
...... and so on
)
Is there a function i can use to do this?
Upvotes: 1
Views: 205
Reputation: 70732
There is no specific map
function, but you can create your own using array_map
or a foreach loop.
function map($n) {
return $n*5;
}
$nums = array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
print_r(array_map(map, $nums));
Or
function map($n, $array) {
foreach ($array as &$val) {
$val *= $n;
}
return $array;
}
$nums = array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
print_r(map(5, $nums));
Output
Array
(
[0] => 5
[1] => 10
[2] => 15
[3] => 20
[4] => 25
[5] => 30
[6] => 35
[7] => 40
[8] => 45
[9] => 50
)
Upvotes: 1
Reputation: 42043
Yes, and it is called array_map
:
$nums = array_map(function($number) { return $number * 5; }, $nums);
Or with array_walk
:
array_walk($nums, function(&$number) { $number *= 5; });
Upvotes: 4
Reputation: 22405
You can easily iterate over the array.
foreach ($nums as &$value) {
$value *= 5;
}
A little more complicated, you can use array_map()
as well.
array_map(function($x) { return $x * 5; }, $nums);
Upvotes: 1