Curriculum
Course: PHP Basic
Login

Curriculum

PHP Basic

PHP Install

0/1

PHP Casting

0/1

PHP Constants

0/1

PHP Magic Constants

0/1

PHP Operators

0/1

PHP Reference

0/276
Text lesson

array_merge()

Example

Combine two arrays into a single array:

<?php
$a1=array(“red”,“green”);
$a2=array(“blue”,“yellow”);
print_r(array_merge($a1,$a2));
?>

Definition and Usage

The array_merge() function combines one or more arrays into a single array.

Tip: You can pass one array or multiple arrays to the function.

Note: If two or more arrays have the same key, the value from the last array overrides the others.

Note: If only one array is passed and it has integer keys, the function returns a new array with integer keys starting at 0 and incrementing by 1 for each value (see example below).

 

Tip: Unlike array_merge(), the array_merge_recursive() function combines values from arrays with the same key into an array, rather than overriding them.

Syntax

array_merge(array1, array2, array3, …)

Parameter Values

Parameter

Description

array1

Required. Defines an array.

array2

Optional. Provides an array.

array3,…

Optional. Indicates an array.

Technical Details

Return Value:

Optional. Indicates an array.

PHP Version:

4+

Changelog:

As of PHP 5.0, this function only accepts parameters of type array.

More Examples

Example

Combine two associative arrays into a single array:

<?php
$a1=array(“a”=>“red”,“b”=>“green”);
$a2=array(“c”=>“blue”,“b”=>“yellow”);
print_r(array_merge($a1,$a2));
?>

Example

Using only one array parameter with integer keys:

<?php
$a=array(3=>“red”,4=>“green”);
print_r(array_merge($a));
?>