[PHP] Merging Arrays

Status
Not open for further replies.

Markshall

Русский Стандарт
Contributor
Dec 18, 2010
2,637
2,389
PHP has a very useful function for merging two or more different arrays into one big array. This function is ' '.

The function is used like this:
PHP:
<?php
$array1 = array( "Mark", "Josh" );
$array2 = array( "Eriksson", "Foskett" );
 
$array_merge = array_merge( $array1, $array2 );
 
echo "<pre>";
print_r( $array_merge );
echo "</pre>";
?>

But there is often a problem with it that I experienced once a twice and needed an efficient way to tackle it. My problem was that it was duplicating keys in the array, so to prevent it, I coded this function to automatically create new keys and return the array:
PHP:
<?php
function safe_merge( &$main_array, &$array_to_merge )
{
    foreach ( $array_to_merge as $k )
    {
        $main_array[] = $k;
    }
   
    return (array) $main_array;
}
$array1 = array( "Mark", "Josh" );
$array2 = array( "Eriksson", "Foskett" );
 
$array_merge = safe_merge( $array1, $array2 );
 
echo "<pre>";
print_r( $array_merge );
echo "</pre>";
?>

I hope you benefited from this simple function,
- Mark.

PS: If you're wondering why I used mine and RastaLulz's name, it's because I was going through iMessage on my iPod and seen his name on there so I thought I'd used it...
 
Status
Not open for further replies.

Users who are viewing this thread

Top