When you are going to shift elements to the right, you can't walk through the array from left to right since you would overwrite values on the next array spot. I also noticed you wrote "i < elements.length - 1". You probably shouldn't add the -1, or you will skip the last value in the array (unless you want that).

First of all, make sure your array has enough space (you will need 1 more), if you are working with primitive types. Therefor you need to create a second array.

Example:

int[] array = new int[prevValue+1];

Now you will have to shift the values to the right, to prevent overwriting the next value we start from the right and go to the left (depends on whether you use the same array or a different array).

for (int i = array.length-1; i >= startPos; i--) {
     elements[i+1] = array[i];
}

Then on the extra spot you reserved you can set a new value:

elements[startPos]=value;

Last but not least, you will have to fill your previous elements (if you are using the same array you can ignore this).

for (int i = 0; i < startPos; i++) {
   elements[i] = array[i];
}
Answer from jetspiking on Stack Overflow
🌐
MDN Web Docs
developer.mozilla.org › en-US › docs › Web › JavaScript › Reference › Global_Objects › Array › shift
Array.prototype.shift() - JavaScript | MDN
The shift() method of Array instances removes the first element from an array and returns that removed element. This method changes the length of the array.
🌐
W3Schools
w3schools.com › jsref › jsref_shift.asp
W3Schools.com
The shift() method removes the first item of an array.
Discussions

shift array elements to the right?
You can use std::rotate using std::rbegin; using std::rend; std::rotate(rbegin(data), rbegin(data) + 1, rend(data)); More on reddit.com
🌐 r/cpp_questions
6
1
February 7, 2020
How can I shift the elements of an array to the right
Please ensure that: Your code is properly formatted as code block - see the sidebar (About on mobile) for instructions You include any and all error messages in full You ask clear questions You demonstrate effort in solving your question/problem - plain posting your assignments is forbidden (and such posts will be removed) as is asking for or giving solutions. Trying to solve problems on your own is a very important skill. Also, see Learn to help yourself in the sidebar If any of the above points is not met, your post can and will be removed without further warning. Code is to be formatted as code block (old reddit: empty line before the code, each code line indented by 4 spaces, new reddit: https://imgur.com/a/fgoFFis ) or linked via an external code hoster, like pastebin.com, github gist, github, bitbucket, gitlab, etc. Please, do not use triple backticks (```) as they will only render properly on new reddit, not on old reddit. Code blocks look like this: public class HelloWorld { public static void main(String[] args) { System.out.println("Hello World!"); } } You do not need to repost unless your post has been removed by a moderator. Just use the edit function of reddit to make sure your post complies with the above. If your post has remained in violation of these rules for a prolonged period of time (at least an hour), a moderator may remove it at their discretion. In this case, they will comment with an explanation on why it has been removed, and you will be required to resubmit the entire post following the proper procedures. To potential helpers Please, do not help if any of the above points are not met, rather report the post. We are trying to improve the quality of posts here. In helping people who can't be bothered to comply with the above points, you are doing the community a disservice. I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns. More on reddit.com
🌐 r/javahelp
7
2
November 7, 2021
sorting - Is it possible to use array_shift() in PHP and get the key? - Stack Overflow
I have a list of files in an array where the filename is the key and the value is the last modified date in seconds. They are sorted from oldest to newest. The files are glob()'d in, and then sor... More on stackoverflow.com
🌐 stackoverflow.com
java - Shift elements of an array - Stack Overflow
I'm writing a code that moves all even numbers to the front of the array and odd numbers to the back. So when an array looks like this: int[] a={1,3,2,5, 4, 7, 8, 6}; the output should look like: ... More on stackoverflow.com
🌐 stackoverflow.com
Top answer
1 of 2
2

When you are going to shift elements to the right, you can't walk through the array from left to right since you would overwrite values on the next array spot. I also noticed you wrote "i < elements.length - 1". You probably shouldn't add the -1, or you will skip the last value in the array (unless you want that).

First of all, make sure your array has enough space (you will need 1 more), if you are working with primitive types. Therefor you need to create a second array.

Example:

int[] array = new int[prevValue+1];

Now you will have to shift the values to the right, to prevent overwriting the next value we start from the right and go to the left (depends on whether you use the same array or a different array).

for (int i = array.length-1; i >= startPos; i--) {
     elements[i+1] = array[i];
}

Then on the extra spot you reserved you can set a new value:

elements[startPos]=value;

Last but not least, you will have to fill your previous elements (if you are using the same array you can ignore this).

for (int i = 0; i < startPos; i++) {
   elements[i] = array[i];
}
2 of 2
1

Here is where your problem is:

for(int i = index; i < elements.length - 1; i++)
{
    elements[i + 1] = elements[i];
}

Lets take your example.

{0, 1, 2, 3} i = 1

You set elements[i + 1], or elements[2] to elements[1]. So, you're new array is {0, 1, 1, 3}. So far so good. But now, when you set 3 to the current number, you set that to the thing you set before. So you will get {0, 1, 1, 1}. The way to avoid this is to iterate from the right, so numbers won't get lost.

🌐
PHP
php.net › manual › en › function.array-shift.php
PHP: array_shift - Manual
array_shift() shifts the first value of the array off and returns it, shortening the array by one element and moving everything down.
🌐
W3Schools
w3schools.com › php › func_array_shift.asp
PHP array_shift() Function
The array_shift() function removes the first element from an array, and returns the value of the removed element.
Find elsewhere
🌐
Mimo
mimo.org › glossary › javascript › array-shift
JavaScript Array shift: Syntax, Usage, and Examples
This pattern ensures the array shrinks each time, ending the loop when all elements are processed. If you’re managing tasks asynchronously, shift() can help:
🌐
Reddit
reddit.com › r/javahelp › how can i shift the elements of an array to the right
r/javahelp on Reddit: How can I shift the elements of an array to the right
November 7, 2021 -

Im trying to add a string into an index of an existing array with inputted values and shift the old values to the right 1 place. for example an array I have created has 5 spaces in total and hold string values is [A, B, C] when I add Z to index 0 the output is [Z, A, A, A] instead of [Z, A, B, C]. I am confused on why it copies the A from index 0 to the other indices of the filled array. Here is the code for my function. curIndex is a integer instance variable that holds the current index of the array.

	public void add (int index, String theData)
	{
		
		for(int i = 0; i < curIndex; i++) 
		{
					
			strarray[i + 1] = strarray[i];
			
		}
		
		strarray[index] = theData;
	}
Top answer
1 of 4
3
Your loop copies the values from left to right so you overwrite the information you need for later indices. Try it out on paper or step through your program with the debugger and you'll see.
2 of 4
1
Please ensure that: Your code is properly formatted as code block - see the sidebar (About on mobile) for instructions You include any and all error messages in full You ask clear questions You demonstrate effort in solving your question/problem - plain posting your assignments is forbidden (and such posts will be removed) as is asking for or giving solutions. Trying to solve problems on your own is a very important skill. Also, see Learn to help yourself in the sidebar If any of the above points is not met, your post can and will be removed without further warning. Code is to be formatted as code block (old reddit: empty line before the code, each code line indented by 4 spaces, new reddit: https://imgur.com/a/fgoFFis ) or linked via an external code hoster, like pastebin.com, github gist, github, bitbucket, gitlab, etc. Please, do not use triple backticks (```) as they will only render properly on new reddit, not on old reddit. Code blocks look like this: public class HelloWorld { public static void main(String[] args) { System.out.println("Hello World!"); } } You do not need to repost unless your post has been removed by a moderator. Just use the edit function of reddit to make sure your post complies with the above. If your post has remained in violation of these rules for a prolonged period of time (at least an hour), a moderator may remove it at their discretion. In this case, they will comment with an explanation on why it has been removed, and you will be required to resubmit the entire post following the proper procedures. To potential helpers Please, do not help if any of the above points are not met, rather report the post. We are trying to improve the quality of posts here. In helping people who can't be bothered to comply with the above points, you are doing the community a disservice. I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns.
🌐
GameMaker
manual.gamemaker.io › beta › en › GameMaker_Language › GML_Reference › Variable_Functions › array_shift.htm
array_shift
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.
🌐
Lucee Documentation
docs.lucee.org › reference › functions › arrayshift()
array.shift() :: Lucee Documentation
pops the first element from an array and shift the rest of the values to the left. In case the array is empty an exception is thrown, unless the second argument "defaultValue" is provided, in that case that value is returned.
🌐
GeeksforGeeks
geeksforgeeks.org › php › php-array_shift-function
PHP array_shift() Function - GeeksforGeeks
June 20, 2023 - This inbuilt function of PHP removes the first element from an array and returns the value of the removed element. After the removal of the first element, the key of the remaining elements is modified and again re-numbered from the start, only ...
🌐
FlatCoding
flatcoding.com › home › php array_shift: remove the first array element with examples
PHP array_shift: Remove the First Array Element with Examples - FlatCoding
September 7, 2025 - The array_shift function in PHP takes the first element from an array and returns it. It also moves all other elements down by one position.
🌐
Medium
medium.com › an-idea › javascript-arrays-push-pop-shift-unshift-adc8fb815fc0
JavaScript Arrays: push(), pop(), shift() & unshift() | by Amanda M Johnson | An Idea (by Ingenious Piece) | Medium
October 10, 2021 - JavaScript Arrays: push(), pop(), shift() & unshift() When working with arrays, it is important to understand the different types of methods and how they transform your data. push(), pop(), shift() …
🌐
Codecademy
codecademy.com › docs › php › arrays › array_shift()
PHP | Arrays | array_shift() | Codecademy
September 9, 2023 - The array_shift() pops the first value of the array off and returns it, shortening the array by one element and shifting each element down.
🌐
Jobtensor
jobtensor.com › Tutorial › PHP › en › Array-Functions-array_shift
PHP Built-in array_shift(), Definition, Syntax, Parameters, Examples | jobtensor
The array_shift() function removes the first element from an array, and returns the value of the removed element.
🌐
Daviddemartini
blog.daviddemartini.com › home › technology › software development › php array_shift() not a function for general use
PHP array_shift() not a function for general use | David DeMartini actual
August 16, 2013 - So, in theory one could use this to get the first element off an array automatically, without removing it. OK, but shift_array does this ANY removes the element. So this is not really the same action. However… (and you know there is a point there), there is another PHP function with a useful side effect.