PHP array merge


Answers ( 1 )


    PHP provides several functions to merge arrays, the most common ones being array_merge() and array_merge_recursive().

    1. Using array_merge():

      • This function merges the elements of one or more arrays together so that the values of one are appended to the end of the previous one.
      • It returns the resulting array.
      • If the input arrays have the same string keys, then the later value for that key will overwrite the previous one. If, however, the arrays contain numeric keys, the later value will not overwrite the original value, but will be appended.
      $array1 = ['color' => 'red', 2, 4];
      $array2 = ['a', 'b', 'color' => 'green', 'shape' => 'trapezoid', 4];
      $result = array_merge($array1, $array2);
    2. Using array_merge_recursive():

      • This function behaves similarly to array_merge(), but if two or more array elements have the same key, it merges them into an array.
      • Useful when you want to combine and preserve all values without losing any through key overwrites.
      $array1 = ['color' => ['favorite' => 'red'], 5];
      $array2 = ['10', 'color' => ['favorite' => 'green', 'blue']];
      $result = array_merge_recursive($array1, $array2);
    3. Using the + Operator:

      • You can also use the + operator to merge two arrays.
      • It appends elements from the right-hand array to the left-hand array while maintaining keys.
      • If there are duplicate keys, the left-hand array's elements will be used, and the right-hand array's elements with the same keys will be ignored.
      $array1 = ['a' => 'apple', 'b' => 'banana'];
      $array2 = ['a' => 'pear', 'b' => 'strawberry', 'c' => 'cherry'];
      $result = $array1 + $array2;

    Remember, the choice of method depends on the specific requirements of your application, such as whether you want to overwrite keys or maintain all values.

Leave an answer