![]() |
Given an array, the task is to remove the first element from an array in PHP. Examples: Input: arr = [1, 2, 3, 4, 5, 6, 7]; Output: 2, 3, 4, 5, 6, 7 Input: arr = [3, 4, 5, 6, 7, 1, 2] Output: 4, 5, 6, 7, 1, 2 Below are the methods to remove the first element from an array in PHP: Table of Content Using array_shift() functionThe Example: This example shows the implementation of the above-explained approach.
Output Removed element: 1 Updated array: Array ( [0] => 2 [1] => 3 [2] => 4 [3] => 5 [4] => 6 ) Using array_slice() functionThe Example: This example shows the implementation of the above-explained approach.
Output Updated array: Array ( [0] => 2 [1] => 3 [2] => 4 [3] => 5 [4] => 6 ) Using unset() FunctionThe unset() function is used to remove the first element from an array. This function takes the array and the index of the element to be removed as arguments. Example: This example shows the implementation of the above-explained approach.
Output Updated array: Array ( [0] => 2 [1] => 3 [2] => 4 [3] => 5 [4] => 6 ) Using array_splice() FunctionThe array_splice() function can remove elements from an array and can also replace them with other elements. By specifying the start index of 0 and a length of 1, you can remove the first element of the array. Example: This example shows the implementation of the above-explained approach.
Output Updated array: Array ( [0] => 2 [1] => 3 [2] => 4 [3] => 5 [4] => 6 ) Using array_shift() and array_values() functionsThe array_shift() function removes the first element from an array and returns it. However, it also re-indexes the array starting from 0. To maintain the original indexing after removing the first element, you can use array_values(). Example:
Output Array ( [0] => 2 [1] => 3 [2] => 4 [3] => 5 [4] => 6 [5] => 7 ) |
Reffered: https://www.geeksforgeeks.org
PHP |
Related |
---|
![]() |
![]() |
![]() |
![]() |
![]() |
Type: | Geek |
Category: | Coding |
Sub Category: | Tutorial |
Uploaded by: | Admin |
Views: | 11 |