PHP Array Merge


 

PHP Array Merge

PHP Array Merge: This PHP tutorial helps you to learn how to merge more than one array in PHP. it includes general format or signature, the value it returns etc. Examples will illustrate this function.

PHP Array Merge: This PHP tutorial helps you to learn how to merge more than one array in PHP. it includes general format or signature, the value it returns etc. Examples will illustrate this function.

PHP Array Merge

In many situations we have to merge two or more than two arrays, we need to use array_merge() function. This function merges or append the elements of one array to the previous array.  

General description of array_merge() is: 

General Format array array_merge(array $var1 [, array $var2 [,.....]])
Parameters $varn: the arrays to be merge

 

Return Value Returns the resulting array

Unlike in PHP 4, PHP 5 only accepts parameters of array() type. You can typecast to merge different types. This point can be clear with the help of example 4 as mentioned below:  

Example 1:

<?php

$array1=array("This","is","first","array");

var_dump($array1);

$array2=array("This","is","second","array");

echo"<br/>";

var_dump($array2);

$array3=array_merge($array1,$array2);

echo"<br/>";

var_dump($array3);

$var="This is a variable";

$array3=array_merge($array1,$var);

var_dump($array3);

?>

Output:

array(4) {
  [0]=>
  string(4) "This"
  [1]=>
  string(2) "is"
  [2]=>
  string(5) "first"
  [3]=>
  string(5) "array"
}

array(4) {
  [0]=>
  string(4) "This"
  [1]=>
  string(2) "is"
  [2]=>
  string(6) "second"
  [3]=>
  string(5) "array"
}

array(8) {
  [0]=>
  string(4) "This"
  [1]=>
  string(2) "is"
  [2]=>
  string(5) "first"
  [3]=>
  string(5) "array"
  [4]=>
  string(4) "This"
  [5]=>
  string(2) "is"
  [6]=>
  string(6) "second"
  [7]=>
  string(5) "array"
}


Warning:  array_merge() [function.array-merge]: Argument #2 is not an array in C:\wamp\www\php\arrayMerge.php on line 12

NULL

Note: As you can see a warning message, it indicates that we cannot merge a variable with an array. We can typecast it into array by array($var), and after that we can easily merge any variable with an array.

 

Ads