This loop is deleting an element from an array with shifting all the elements in front of it back one step.
For example let assume the prices
array is something like this:
prices=[250,270,230,400,1000,200]
The delete_element
function gets an uint argument called index
. Let assume it gets 2 as index
. In the for loop uint i = index
is declaring a temporary variable i
and assigning index
to it which in our example means i = 2
.
After ;
you see i < prices.length-1
this is the ending condition which means this for loop will loop till the the value of i
is less than prices.length-1
and as soon as the i
becomes equal to prices.length-1
the loop is over. prices.length
in here is 6 since we have 6 elements in the prices
array, hence prices.length-1 = 5
so the loop will end after i = 4
.
The next code is i++
which means increase i
in the loop by one each time the loop occurs in order to loop the i
from 2 all the way up to 5.
Inside the for loop we have prices[i] = prices[i+1];
it means assign the next element to the previous element. In the first loop it'll be like this :
prices[2] = prices [3];
Inside prices[2]
we have 250 and inside prices[3]
is 400. so after this one loop our whole array will loop like this:
prices=[250,270,400,400,1000,200];
The next loop i
will increase to 3 so we will have
prices[3] = prices [4];
Which will change the array to this:
prices=[250,270,400,1000,1000,200];
and the next loop will change the array to this:
prices=[250,270,400,1000,200,200];
The next line prices.length--;
is deleting the last element of array which will make the array to this:
prices=[250,270,400,1000,200];
now the prices.length
is 5 instead of 6.
Be Careful
This code only works for solidity version 0.5.x
and lower. In new solidity 0.6.x
and higher you can't do this prices.length--;
. The length
is now only readable and you can't assign any number to it. in order to delete the last element of an array and decrease the size by 1 you can now use prices.pop()