The Most Active and Friendliest
Affiliate Marketing Community Online!

“Adavice”/  “1Win

Tip : merging arrays in php

D

dman_2007

Guest
If you want to merge mulitple arrays into one array in php, you can do it either by using array_merge function or by using + operator. Each of these methods handle elements with duplicate keys differently.

1) array_merge function

When using array_merge function, if more then one input array has same string keys, then the later value for that key from later input array will overwrite values from previous arrays. However, if more then one array contain same numeric keys, later value will not overwrite previous values. Instead, the resultant array will contain all the values taken sequentially from first array to last array indexed in a continuous way. This is the case even if the arrays do not contain any value with same numeric key.For example, take a look at the following code

Code:
<?php
 $array1 = array('name' => 'matthew', 5 => 1, 2);
 $array2 = array("a", "b", "c", 'name' => 'joe');
  
 $array3 = array_merge($array1, $array2);
  
 print_r($array3);
?>

Thisis the output this code produces :

Array ( [name] => joe [0] => 1 [1] => 2 [2] => a [3] => b [4] => c )

Since both $array1 and $array2 contains elements with 'name' key, value from the later array i.e. $array2 overwrites the value from previous array i.e. $array1. Also take a look at the numeric keys, both array have elements with numeric key 0, but none of them overwrites the other. Both of them are present in the resultant array with the final key based on their overall position in the sequence of array elements with numeric keys from all the input arrays. Note that even though we specifically assigned numeric key 5 to the value 1 in the first array and there is no other element in any array with the same key, but still it has been given a new key based on its position.

2) + operator

+ operator is relatively simple, when merging arrays unlike array_merge function no reindexing will be done i.e. keys value will be preserved for each array element and when elements with same keys are encountered in later arrays, they will be ignored. For example, when the same arrays which were used in previous example are merged using + operator instead of array_merge function :

Code:
<?php
  $array1 = array('name' => 'matthew', 5 => 1, 2);
  $array2 = array("a", "b", "c", 'name' => 'joe');
  
  $array3 = $array1 + $array2;
  
  print_r($array3);
?>

This is what the resultant array will look like :

Array ( [name] => matthew [5] => 1 [6] => 2 [0] => a [1] => b [2] => c )
 
Merging two arrays together is a one step command called array_merge.
<?php
$pantry_food = array_merge ($pantry, $pantry2);
?>
__________________________________________________________
Web site Design
 
Last edited by a moderator:
MI
Back