Post Reply 
 
Thread Rating:
  • 1 Votes - 5 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Customized Merge Array Function
06-10-2010, 12:29 PM
Post: #1
Wink Customized Merge Array Function
Hey friends today while I was coding i found a issue with merge array function

PHP Code:
array_merge($array1,$array2); 

This is the function you can read the further documentation here

http://php.net/manual/en/language.types.array.php

Now While I was coding , here is my code

PHP 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

Code:
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[/code] 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.

PHP Code:
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 that function to merge two arrays Smile now you can see my full code here

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

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

and this one works perfectly Smile . Here is the output Smile

[code]
1 one
2 two
3 three
4 four
one 1
two 2
three 3
four 4
[code]

Now you can see that output has corrected Smile

No one ever promised me that the path I have chosen will be easy and no one ever promise me to accompany me . So i have to figure out the solutions of my own and the day I will quit will be the day when I will die.

Rockey Killer
GTALK - skg102@gmail.com
Orkut - skg102@gmail.com
Facebook - skg102@gmail.com
Yahoo - rockeykiller@ymail.com
Twitter - rockeykiller

:-? bas baki profiles abhi mughey banani hain Tongue
Visit this user's website Find all posts by this user
Quote this message in a reply
Post Reply 


Forum Jump: