var arr = [ "We", "learn", "JavaScript" ]; // Declare array of length 3
var oldFirstElement = arr.shift(); // First element now deleted
// Show returned value on one line, new array length on the next:
alert( oldFirstElement +"\nNew length of: "+ arr.length );
Tip: shift() will return "undefined" if the array is empty (length of zero).
var arr = [ 0, 2, 4, 6, 8, 10, 12, 14, 16, 18 ]; // Array of 10 numbers
for( var i=0; i<3; ++i ) // Remove first 3 elements
arr.shift();
// Now check "new" array's length, and all its elements:
alert( "New length is: " + arr.length + "\n" + arr.join("-") );
Note: we used the join() method to show all elements with a hyphen inserted between each one.
$arr = array( 'We', 'learn', 'PHP' );
$oldFirstElement = array_shift($arr);
// Code below prints: Element 'We' removed - new length = 2
echo "Element '$oldFirstElement' removed - new length = " . count($arr);
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.