Merging Numeric Arrays with Preserved Keys
Often, we encounter the need to combine two arrays without introducing duplicates or altering their original keys. To achieve this, let's explore the various methods available in PHP.
Using array_merge:
The array_merge() function provides a straightforward way to combine two arrays. By default, it overwrites duplicate keys with the values from the latter array. In this case, since the arrays have string keys, which are treated as integers in PHP, the keys get renumbered. To preserve the original keys, we can use:
$output = array_merge($array1, $array2);
Using array_combine:
If the keys are crucial, we can utilize array_combine() to recreate the array with the desired keys. The syntax is:
$output = array_combine($output, $output);
Using the ' ' Operator:
Another elegant solution is to use the ' ' operator, which natively merges arrays and preserves their keys. This is the recommended method:
$output = $array1 + $array2;
Example:
Consider the example arrays:
$array1 = array( '11' => '11', '22' => '22', '33' => '33', '44' => '44' ); $array2 = array( '44' => '44', '55' => '55', '66' => '66', '77' => '77' );
Using the suggested methods, we can obtain the following output:
$output = array( '11' => '11', '22' => '22', '33' => '33', '44' => '44', '55' => '55', '66' => '66', '77' => '77' );
The above is the detailed content of How Can I Merge Numeric Arrays in PHP While Preserving Original Keys?. For more information, please follow other related articles on the PHP Chinese website!