var arr = [ "I", "learn", "JavaScript" ];
alert( "Array before:\n" + arr.join(" ") );
// Assign to self, because concat() returns *copy* of new array:
arr = arr.concat( "and", "it's", "fun" );
alert( "Array after:\n" + arr.join(" ") ); // Click to run ->
Note: the String object also has a concat() method to append one or more strings to another.
var arr = [ "I", "learn", "JavaScript" ];
var arr2 = [ "this", "is", "another", "array" ];
arr = arr.concat( arr2 );
alert( arr +"\nNew number of elements = "+ arr.length );
var arr = [ "I", "learn", "JavaScript" ];
arr = arr.concat( [ [ 1, 2, "hello" ] ] ); // Add other array as element
alert( "Array after:\n" + arr.join("\n") );
Tip: the last line uses the join() method with escaped "n" to display one element per line. Notice that the last line is comma-separated: in this case, it tells you that it is itself an array! Passing array elements without double square brackets would add them as new elements, not as an array.
var arr = [ "I", "learn", "JavaScript" ];
arr[ arr.length ] = "today"; // add 1 to last element index (arr.length-1)
alert( arr.join("\n") );
$arr1 = array( 'I', 'learn', 'PHP' );
$arr2 = array( 'and', "it's", 'fun' );
$arr1 = array_merge( $arr1, $arr2 ); // $arr1 now contains 6 elements
print_r( $arr1 ); // [0]=I [1]=learn [2]=PHP [3]=and [4]=it's [5]=fun
Sister methods - array insertion and deletion:
• concat() adds elements or arrays at the end of an array, and returns a copy of the new array.
• unshift() adds an element to the start of an array ("prepends"), and returns the new length.
• push() adds an element to the end of an array ("appends"), and returns the new length.
• shift() removes the first element of an array, and returns its value.
• pop() removes the last element of an array, and returns its value.