In this write-up, we will be discussing about the difference between array_shift() and array_unshift() functions in php.
The function array_shift() is used to move the first value of the array to another variable and the result will show a reduced value of array having the shifted array moved out from it.
The function array_unshift() is used to add one or more array elements to the input array. They are added in the beginning of the input array. It performs function opposite to the array_shift() function.
The difference between the two is described below with examples of each and with the return value. Join Our php training and learn all the functions used in advanced php development.
ARRAY_SHIFT() FUNCTION
As described in the above section, the array_shift() function is used in php programming language to move/ shift the first value of the array of elements resulting in the absence of the shifted value in the output i.e, the return value will not show the shifted element of the array.
Syntax : array_shift($arr);
A single parameter $arr is used in this function which represents the array of elements from which one element is to be moved away.
Result / Return Value : On the successful execution of the function, the shifted value will be returned. And if the array is left empty, Null will be returned.
Example : An example of array_shift() function is shown below.
Output : You will get the following output after successfully running the above php script. Clearly, in the above example, from the three values of the array elements namely ‘blue’, ‘orange’ and ‘yellow’ first value ‘blue’ has been shifted as shown in the image below.
ARRAY_UNSHIFT() FUNCTION
As described earlier in this article, array_unshift() function is used to add one or more mixed values in the beginning of the array of elements.
Syntax : array_unshift($input_arr, $arr1, $arr2, $….);
Two types of parameters are used in this function which are described below.
- $input_arr- This parameter represents the input array to which value is to be added.
- $arr1- This parameter represents the first value to be added to the input array. More values can also be added $arr2, $arr3, $….
Result / Return Value : The successful execution of the function will return a newly formed array of elements.
Example : We have shown below an example of array_unshift() function.
Output : The following output will be generated after running the above php script. Clearly, we have added two new values ‘green’ and ‘red’ to the input array that already has values ‘blue’ and ‘yellow’. On the successful execution of the script, a new array will be returned having the previous and the newly added values as shown in the image below.
We have provided you the best possible information about difference between array_shift() and array_unshift() functions in php. Hope you liked this article. For more information and related updates, stay connected to our php blogs.