# Merge Array Function Problem :(

#### Do you have a question? Post it now! No Registration Necessary.  Now with pictures!

•  Subject
• Author
• Posted on

While I was coding , here is my code

\$array1 = array(
'1' => 'one',
'2' => 'two',
'3' => 'three',
'4' => 'four'
);
\$array2 = array();
foreach(\$array1 as \$key => \$v) {
\$array2[\$v] =  \$key;
};
\$newarray  = array_merge(\$array1,\$array2);
foreach(\$newarray as \$key => \$v) {
echo \$key."    ".\$v."\n";
};

Result that I got was

0    one
1    two
2    three
3    four
one    1
two    2
three    3
four    4

Now you can see the index and key have changed and now 0 is written in-
front of one , obviously I wasn't expecting that but i can hardly find
any solution for this . So I decided to  write my own function for
merging two arrays.

Here is my function

function mergearray(\$array1,\$array2) {
\$array3 = array();
foreach(\$array1 as \$key => \$v) {
\$array3[\$key] =  \$v;
};
foreach(\$array2 as \$key => \$v) {
\$array3[\$key] =  \$v;
};
return \$array3;
};

You can use it to merge 2 arrays :)
You can further discuss over it here ,

## Re: Merge Array Function Problem :(

El 10/06/2010 6:43, rockey killer escribió/wrote:

Or:

\$array2 = array_flip(\$array1);

\$newarray  = \$array1 + \$array2;

> So I decided to  write my own function for

Sooner or later, we all reimplement some built-in array function :)

--
-- http://alvaro.es - Álvaro G. Vicario - Burgos, Spain
-- Mi sitio sobre programación web: http://borrame.com
-- Mi web de humor satinado: http://www.demogracia.com
--

## Re: Merge Array Function Problem :(

rockey killer wrote:

You could have done easier and better with

\$newarray = array_merge(\$array1, array_flip(\$array1));

print_r(\$newarray);

is a bit easier.

As expected.

You should have.  The key of the first element of the flipped array must be
'0'.

Or you could prepend the required number of elements to the flipped array
before merging, e.g.:

\$a = array('1' => 'one', '2' => 'two');
\$a2 = array_flip(\$a);
array_unshift(\$a2, '');
print_r(array_merge(\$a2, \$a));

Generalizing this solution is left as an exercise to the reader.

Forget it.  Post here, read here.

PointedEars
--
Danny Goodman's books are out of date and teach practices that are
positively harmful for cross-browser scripting.