HomePHPDifference between array_merge() and array_combine().

Difference between array_merge() and array_combine().

๐Ÿ”น array_merge()

  • Definition: Merges one or more arrays into a single array.
  • Behavior:
    • Numeric keys are reindexed (0,1,2,…).
    • String keys are preserved, and if the same key exists in multiple arrays, the later one overwrites the earlier one.

Example:

$a = ["red", "green"];
$b = ["blue", "yellow"];

print_r(array_merge($a, $b));

Output:

Array
(
    [0] => red
    [1] => green
    [2] => blue
    [3] => yellow
)

With duplicate string keys:

$a = ["color" => "red", "shape" => "circle"];
$b = ["color" => "blue", "size" => "large"];

print_r(array_merge($a, $b));

Output:

Array
(
    [color] => blue    // overwritten
    [shape] => circle
    [size] => large
)

โœ… Use array_merge() when you want to combine values of multiple arrays.


๐Ÿ”น array_combine()

  • Definition: Creates an array by using one array for keys and another array for values.
  • Condition: Both arrays must have the same number of elements, otherwise it throws an error.

Example:

$keys = ["a", "b", "c"];
$values = [1, 2, 3];

print_r(array_combine($keys, $values));

Output:

Array
(
    [a] => 1
    [b] => 2
    [c] => 3
)

โš ๏ธ If the sizes donโ€™t match:

$keys = ["a", "b"];
$values = [1, 2, 3];
print_r(array_combine($keys, $values));

Error:

Warning: array_combine(): Both parameters should have an equal number of elements

โœ… Use array_combine() when you want to map keys to values explicitly.


๐Ÿ”‘ Key Differences

Featurearray_merge()array_combine()
PurposeCombines multiple arraysCreates new array from keys & values
Keys handlingNumeric keys reset; String keys preservedFirst array = keys, Second array = values
OverwritingLater arrays overwrite same string keysNo overwrite (direct mapping)
Size restrictionAny number of arraysBoth arrays must have equal length
Example Use CaseMerging config arrays, appending listsCreating dictionary-like structures

๐Ÿ‘‰ In short:

  • Use array_merge() when you want to join arrays.
  • Use array_combine() when you want to pair keys with values.

Share:ย 

No comments yet! You be the first to comment.

Leave a Reply

Your email address will not be published. Required fields are marked *