2

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!

2
  • Magic in coding?? Coding Itself is creating magic. Commented Jan 8, 2015 at 11:28
  • if you know that the sequence is 0,2,4,..... you don't need to store in array because you know ith number is 2*(i-1) ( 1 based index) Commented Jan 8, 2015 at 11:29

3 Answers 3

5

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
)
Sign up to request clarification or add additional context in comments.

3 Comments

Maybe you could add an example for OP, otherwise it's a nice answer
SUPERB! :)))))))))))))))))))))))))
@iprophesy Please don't spam with smiles and so on also don't use caps! You can write something like: Thanks this worked for me or something like that
2

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);

2 Comments

And how is this adding an element to an array?
@violator667 Err... Yeah, fine. All possible ways I said.
-1

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
)

1 Comment

And why a -1? This answers the OPs question.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.