ajsie
ajsie

Reputation: 79686

add values from arrays to an array?

how do i add values from arrays to an array so that it grows by time.

eg.

all values form array1 to myArray.

all values form array2 to myArray.

so now myArray contains all values from 1 and 2.

i want to do this in a cpu efficient way

Upvotes: 4

Views: 176

Answers (2)

Alix Axel
Alix Axel

Reputation: 154513

Either use the array_merge() function (also see array_merge_recursive()):

$myArray = array_merge($array1, $array2);

If the input arrays have the same string keys, then the later value for that key will overwrite the previous one. If, however, the arrays contain numeric keys, the later value will not overwrite the original value, but will be appended.


Or use the Union Array Operator (+):

$myArray = $array1 + $array2;

The + operator appends elements of remaining keys from the right handed array to the left handed, whereas duplicated keys are NOT overwritten.

Upvotes: 2

Tyler Carter
Tyler Carter

Reputation: 61557

$myArray = array_merge($array1, $array2);

See the documentation, as there are a few things you will want to know about how duplicates and numerical keys are handled.

Upvotes: 4

Related Questions