faqts : Computers : Programming : Languages : PHP : kms : General

+ Search
Add Entry AlertManage Folder Edit Entry Add page to http://del.icio.us/
Did You Find This Entry Useful?

41 of 57 people (72%) answered Yes
Recently 4 of 10 people (40%) answered Yes

Entry

How can I a concatenate two arrays together?
How can I merge two arrays?

Nov 16th, 2001 14:55
Dave Benjamin, Nathan Wallace,


Note: PHP4 offers array_merge(), which does preserve keys.
http://www.php.net/manual/en/function.array-merge.php
--

The difference between a merge and a concat is perhaps subtle.  The
basic difference is that in a merge only unused indices in the first
array will be filled by the second array.

So, if you try to add: array(1,2,3) + array(4,5,6)
you will end up with a 3-element array containing just (1,2,3)

However, if you add: array(1,2,3) + array(4,5,6,7,8,9)
you will end up with a 6-element array containing (1,2,3,7,8,9)

Quite different from a concatenation.  The only way it is guaranteed to
work as a concatenation is when the two array do not have any
overlapping indices.

There isn't a simple way to cat arrays.  The simplest way is probably
something like this:

    $a = array(1,2,3);
    $b = array(4,5,6);
    $c = $a;  
    while(list(,$v)=each($b)) {
        $c[] = $v;
    }

At this point the $c array will contain (1,2,3,4,5,6)

Merging can be useful for keyed arrays.  If you have:

    $foo = array(a=>b, c=>d);
    $bar = array(e=>f, g=>h);

then do:

    $boo = $foo + $bar;

merging the two arrays to get the result:

    $boo = array(a=>b, c=>d, e=>f, g=>h);

If you have:

    $foo = array(a=>b, c=>d);
    $bar = array(a=>f, g=>h);

then do:

    $boo = $foo + $bar;

merging the two arrays to get the result:

    $boo = array(a=>f, c=>d, g=>h);