PHP array_merge() Function

PHP

PHP array_merge() - Merge Arrays

The array_merge() function in PHP is a powerful tool used to combine multiple arrays into a single array. This function appends the values from subsequent arrays to the first array, effectively concatenating them. Whether you need to combine configuration options, user data, or any form of indexed or associative arrays, array_merge() offers a straightforward solution.

Prerequisites

  • Basic knowledge of PHP syntax
  • Understanding of PHP arrays (indexed and associative)
  • PHP environment setup (version 5.0.0+ recommended)

Setup Steps

  1. Ensure you have PHP installed on your system. You can download it from php.net.
  2. Set up a PHP file with your preferred code editor, e.g., merge-arrays.php.
  3. Write PHP code using array_merge() to combine arrays as needed.
  4. Run the script from the command line using php merge-arrays.php or in a web server environment.

Understanding PHP array_merge() Function

The array_merge() function accepts one or more arrays as arguments and returns a new array containing all the elements from these arrays.

Function Signature

array array_merge(array ...$arrays)

Key behavior:

  • For indexed arrays, the values of subsequent arrays are appended to the first array, reindexing numeric keys.
  • For associative arrays, if keys overlap, values from later arrays overwrite those from earlier arrays.

Examples Explained

Example 1: Merging Indexed Arrays

<?php
$array1 = ['apple', 'banana'];
$array2 = ['orange', 'grape'];

$result = array_merge($array1, $array2);
print_r($result);
?>

Output:

Array
(
    [0] => apple
    [1] => banana
    [2] => orange
    [3] => grape
)

Here, the elements of $array2 are appended to $array1. Numeric keys are reindexed sequentially.

Example 2: Merging Associative Arrays

<?php
$array1 = ['a' => 'red', 'b' => 'green'];
$array2 = ['b' => 'blue', 'c' => 'yellow'];

$result = array_merge($array1, $array2);
print_r($result);
?>

Output:

Array
(
    [a] => red
    [b] => blue
    [c] => yellow
)

Since both arrays have the key 'b', the value from $array2 ('blue') overwrites the value from $array1.

Example 3: Mixing Indexed and Associative Arrays

<?php
$array1 = [0 => 'first', 1 => 'second'];
$array2 = ['key' => 'value', 0 => 'third'];

$result = array_merge($array1, $array2);
print_r($result);
?>

Output:

Array
(
    [0] => first
    [1] => second
    [2] => value
    [3] => third
)

Note that numeric keys from both arrays are reindexed starting from zero, while string keys become part of the merged array. The string key 'key' had a numeric key 0 in the array, but in this case the value is treated as a string key.

Best Practices

  • Avoid key collisions: When merging associative arrays, ensure keys don’t unintentionally overwrite important data.
  • Use for combining similar datasets: Best suited to arrays with related or compatible keys.
  • Consider array_merge_recursive() for deeply nested arrays: Where multiple values need to be merged into sub-arrays.
  • Check data types: Merging arrays with mixed data types can produce unexpected results if not carefully managed.

Common Mistakes

  • Expecting array_merge() to preserve numeric keys β€” it always reindexes numeric keys starting from 0.
  • Forgetting that associative keys get overwritten by later arrays in the argument list.
  • Using array_merge() when array union (+) operator would be more appropriate to preserve keys.
  • Assuming array_merge() modifies the original arrays β€” it returns a new array without affecting the inputs.

Interview Questions

Junior-Level Questions

  • Q1: What does array_merge() do in PHP?
    A: It combines one or more arrays into a single array by appending values.
  • Q2: How does array_merge() handle numeric keys?
    A: It reindexes numeric keys starting from zero in the resulting array.
  • Q3: Does array_merge() modify the original arrays?
    A: No. It returns a new array instead of modifying the inputs.
  • Q4: What happens when merging two associative arrays with the same keys?
    A: Values from the later array overwrite those from the earlier one.
  • Q5: Write a simple example of merging two indexed arrays.
    A:
    <?php
    $array1 = [1, 2];
    $array2 = [3, 4];
    print_r(array_merge($array1, $array2));
    ?>

Mid-Level Questions

  • Q1: How is array_merge() different from the array union operator (+)?
    A: array_merge() appends and reindexes numeric keys; the union operator preserves keys and does not overwrite existing keys.
  • Q2: What will be the output of merging $a = [0 => 'x'] and $b = [1 => 'y'] with array_merge()?
    A: [0 => 'x', 1 => 'y'] β€” numeric keys will be reindexed sequentially.
  • Q3: Can array_merge() handle objects inside arrays?
    A: Yes, it merges arrays regardless of the data type of values.
  • Q4: If duplicated string keys exist in merged arrays, which array’s values will persist?
    A: Values from later arrays overwrite earlier ones.
  • Q5: How to merge arrays recursively and preserve all duplicate keys?
    A: Use array_merge_recursive(), which merges values of duplicate keys into arrays.

Senior-Level Questions

  • Q1: Explain why array_merge() reindexes numeric keys and how this impacts large datasets?
    A: It creates a contiguous zero-based index to avoid conflicts with duplicated numeric keys. For large datasets, this may affect performance and key integrity.
  • Q2: How can you merge two associative arrays without overwriting keys?
    A: Use the array union operator (+), which preserves keys from the first array.
  • Q3: When might array_merge_recursive() cause issues?
    A: It can produce nested arrays unexpectedly if keys overlap, which complicates data handling.
  • Q4: How to merge arrays and preserve numeric keys exactly as in source arrays?
    A: Use the array union operator or manually merge arrays without using array_merge() since it always reindexes numeric keys.
  • Q5: Describe a situation where array_merge() would be preferred over alternatives.
    A: When appending or combining indexed arrays where reindexing numeric keys is acceptable or desired, such as merging list items.

FAQ

Q: Does array_merge() preserve the keys of numeric arrays?

A: No, numeric keys are always reindexed starting from zero.

Q: Can array_merge() merge arrays with different data types?

A: Yes, it merges arrays regardless of the data types of their values.

Q: How to merge arrays without overwriting associative keys?

A: Use the array union operator (+), which preserves keys from the first array and ignores duplicates from the second.

Q: Is array_merge() suitable for multi-dimensional arrays?

A: It merges only the first level. Use array_merge_recursive() for deeper merging.

Q: What happens if array_merge() is called with no arguments?

A: It returns an empty array.

Conclusion

The PHP array_merge() function is essential for appending values from subsequent arrays to the first array, enabling easy array concatenation. By understanding how it handles numeric and associative keys, you can effectively combine arrays without losing data or causing unexpected key conflicts. Always consider your specific use case and whether you want to preserve keys or reindex them when choosing between array_merge(), the array union operator, or other merging functions.