Reputation: 185
I was wondering if it's possible to add a values to an array without using loops.
Yes, I know that technically I can write :
$myArray = array(0,2,4,6,8,10,12,14,16,18,20,22,24,26,28,30,32); //etc...
But as you can see on the example if the line is very long it's smarter to do it with a loop.
Now since I already know that each number will be raised by +2 I was wondering if there is internal php command right of the box so I can do it with a callback or any other magic trick ;)
Not the correct syntax but just so you can get the idea.
$myArray = Array();
$myArray[] = insertArray($valueOf{$x};$x;$x>=100;$x=+2);
Yea, I know that this can also applied as a function/class but I'm asking if I can do that magic RIGHT OF THE BOX :)
Thanks!
Upvotes: 2
Views: 2159
Reputation: 10447
You can do this with range()
(PHP Manual). To produce your array do:
$array = range(0, 32, 2);
The last variable is the number of steps to make between each entry in the array. It defaults at one but by setting it to 2 each number will increment by 2.
print_r($array);
produces
Array
(
[0] => 0
[1] => 2
[2] => 4
[3] => 6
[4] => 8
[5] => 10
[6] => 12
[7] => 14
[8] => 16
[9] => 18
[10] => 20
[11] => 22
[12] => 24
[13] => 26
[14] => 28
[15] => 30
[16] => 32
)
Upvotes: -1
Reputation: 167182
Yes, you have something called array_walk
. Define a function like this:
function addTwo (&$item, $key)
{
$item = $item * 2;
}
Then use the function this way:
array_walk ($myArray, 'addTwo');
In your use case, you can either use range()
with the skip
option or, you can use this way:
array_walk (range (0, $max));
Or, with range()
:
range (0, $max, 2);
Upvotes: 2
Reputation: 499
You can create an array containing a range of elements using range()
it supports skip
parameter
$a = range(0,10,2);
print_r($a);
Array
(
[0] => 0
[1] => 2
[2] => 4
[3] => 6
[4] => 8
[5] => 10
)
Upvotes: 5