This function removes the first element from the given array and returns it.
Because of this, all other elements are shifted to the left one place, i.e. the value at index 0 is removed, the value at index 1 moves to index 0, the value at index 2 moves to index 1, etc. The number of elements is reduced by 1, as there is no value to replace the last element with.
The function works identically to array_pop, but removes and returns the first element instead of the last one.
NOTE Use array_first to get the first element without removing it from the array.
array_shift(array);
Argument | Type | Description |
---|---|---|
array | Array | The array to shift, i.e. to return and remove the first element from |
Any (the type of the removed first array element)
var _array = ["A", "B", "C"];
repeat(2)
{
array_shift(_array);
}
show_debug_message(_array);
The above code calls array_shift on the array _array twice. After that, a debug message shows the contents of the array. As the first call to the function removes the value "A" and the second shift removes the value "B", the array will only contain "C" at this point.
var _queue = [];
var _incoming = ["S", "O", "M", "E", " ", "L", "E", "T", "T", "E", "R", "S"];
MAX_QUEUE_LENGTH = 4;
var _len = array_length(_incoming), i = 0;
repeat(_len)
{
array_push(_queue, _incoming[i]);
if (array_length(_queue) > MAX_QUEUE_LENGTH)
{
array_shift(_queue);
}
i++;
}
The above code creates a temporary array _queue that acts like a queue using array_shift and array_push. The characters in a second array _incoming are added to the queue array one by one, using a repeat loop. Whenever the length of the queue is greater than 4 (stored in the constant MAX_QUEUE_LENGTH), the first element is removed using array_shift.
var _array = ["F", "O", "R", "E", "V", "E", "R"];
repeat(10)
{
array_push(_array, array_shift(_array));
show_debug_message(_array);
}
In the above example the array _array is "rotated" 10 times. "Rotating" an array means that elements are removed on one end and added back on the other end. The length of the array remains the same. Every iteration, the letters move left; the array is rotated left. A debug message is shown after each iteration to show the contents of the array at that point.
Using the functions array_pop and array_insert arrays can be rotated right instead.