// Declare array with two elements:
var arr = [ "learn", "JavaScript" ];
// Add new element, and store new length:
var newLength = arr.unshift("We");
// Check new length and content of array:
alert( newLength +"\n"+ arr.join(" ") );
Note: use join() to "glue" pieces of an array into a string (with a space character, in this case).
var arr = [ 3, 4, 5, 6 ]; // Declare an array of 4 elements
// Pass the new elements to insert as arguments
arr.unshift( 0, 1, 2 );
// Display each element of the updated array on its own line:
alert( arr.join("\n") );
$arr = array( 'learn', 'PHP' );
$newLength = array_unshift( $arr, 'We', 'decided', 'to' );
echo "Elements count is $newLength; content is:<br>";
print_r( $arr ); // Display each element
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.