Arrays in PHP are variables that can holds multiple values. There are many methods for accessing and manipulating arrays. The methods array_slice () and array_splice () are widely used methods for array manipulations.
The array.slice () removes items from the array and then return those removed items as an array whereas array. Splice () method is selected items from an array and then those elements as a new array object.
It looks first that both are same in working, but there are various differences between them which we are going to discuss in this particular blog, let’s start with major difference between array_slice () and array_splice ().
Difference between array_slice () and array_splice ()
Array_slice ()
The array.slice () removes items from the array and then return those removed items as an array.
- This array method forms a new array after execution in a sub-array of a given array.
- There are 3 parameter in this function, First array_name, ‘start’ indicates the starting index and ‘end’ indicates the ending index and after selected array name.
Syntax: – array_slice ($array_name, start, end);
- The changes do not reflect in the original array, original array remain the same. The result has to be assigned to a new array variable.
- The value come in new array with the values in the selected sub-array of the given array. The values in the range start to (end-1) will be selected.
Example:-
Output:-
Array ( [0] => bittu [1] => nilesh [2] => santosh [3] => amit )
Array ( [2] => bittu [3] => nilesh [4] => santosh [5] => amit )
Array ( [c] => bittu [d] => nilesh [e] => santosh [f] => amit )
Array ( [3] => nilesh [4] => santosh )
array_splice ()
The array. Splice () method is selected items from an array and then those elements as a new array object.
- This method is used to remove an item from the given array and also used to add new element in array.
- There are mainly 4 parameter in this function, first ‘array_name’, second is starting point, and 3 is end point and last is 2nd array_name which we wish to add in this array at the place of deleted values.
- The changes reflect in the original array, no need to assigned result to any other new variable.
- The return value is an array containing the deleted element.
Example:-
Output:-
Array ( [0] => manish [1] => rakesh [2] => tittu [3] => rittu )
Array ( [0] => manish [1] => rakesh [2] => tittu [3] => rittu )
Array ( [0] => manish [1] => rakesh [2] => mj [3] => cull [4] => notly )
Conclusion
array_slice() and array_splice() are very useful methods that you must know in PHP, they sound pretty much similar, but they are completely different in the way they work. It is very good thing to know the exact working and their deffrences.
Thank you for reading this article. I hope you found it useful.
Keep Practising and exploring.