![]() |
Given an Array, the task is to remove the first element from the array in PHP. There are three methods to remove the first element from an array, these are – using array_shift(), array_slice(), and unset() functions. Let’s explore each method with detailed explanations and code examples. Table of Content Approach 1: Using array_shift() FunctionThe array_shift() function removes the first element from an array and returns it. This function modifies the original array.
Output Removed element: 10 Updated array: Array ( [0] => 20 [1] => 30 [2] => 40 [3] => 50 [4] => 60 ) Approach 2: Using array_slice() FunctionThe array_slice() function is used to extract a slice of an array. By specifying the start index as 1, you can remove the first element from the array.
Output Updated array: Array ( [0] => 20 [1] => 30 [2] => 40 [3] => 50 [4] => 60 ) Approach 3: Using unset() FunctionYou can also use the unset() function to remove the first element from an array. This function takes the array and the index of the element to be removed as arguments.
Output Updated array: Array ( [0] => 10 [1] => 20 [2] => 30 [3] => 40 [4] => 50 [5] => 60 ) Approach 4: Using array_splice() FunctionThe array_splice() function can be used to remove elements from an array and optionally replace them with other elements.
Output Array ( [0] => 2 [1] => 3 [2] => 4 [3] => 5 ) Approach 5: Using the array_diff_key() FunctionThis method involves using the array_diff_key() function to remove the first element from an array by comparing keys. The array_diff_key() function compares the keys of two arrays and returns the differences. This approach is beneficial when you want to remove the first element based on its key, especially in associative arrays where keys are not necessarily numeric. Example: Here’s how you can use array_diff_key() to remove the first element from both numeric and associative arrays. First, identify the key of the first element, then create a temporary array with this key and use array_diff_key() to remove it.
Output Array ( [b] => banana => cherry ) Approach 6: 5. Using a LoopIn this approach we will shifting the all elements of the array to the left using a loop and then remove the last element.
Output Array ( [0] => e [1] => e [2] => k ) |
Reffered: https://www.geeksforgeeks.org
PHP |
Type: | Geek |
Category: | Coding |
Sub Category: | Tutorial |
Uploaded by: | Admin |
Views: | 16 |