![]() |
Given an array “myArray”, the task is to remove an element from its end. This operation is important in scenarios involving stacks, queues, and web development. In PHP, there are several approaches to achieve this One common method is using the array_pop() function, which removes the last element from the array. For instance, if “myArray” initially contains string elements and we apply array_pop() to remove ‘date’ from its end, the modified array can be displayed using “print_r($myArray)”, showcasing the updated contents without ‘date’. Example: Input: $myArray = ["apple", "banana", "cherry", "date"]; These are the following approaches: Using the unset() function with the last indexWe are going to use the unset() function in the PHP arrays which are the ordered maps and use the integer keys starting from 0. To remove an element from the end of an array using unset(), we specify the index of the last element in the array. Example: To demonstrate removing an element from the end of the array using unset() function in PHP.
Output Original array: 1, 2, 3, 4, 5 Modified array: 1, 2, 3, 4 Using the array_pop() functionWe are going to use the array_pop() function that is used to remove the last element from an array and returns the removed element. Example: To demonstrate removing an element from the end of the array using arrya_pop() function in PHP.
Output Original array: 1, 2, 3, 4, 5 Modified array: 1, 2, 3, 4 Removed element: 5 Using the array_slice() functionWe are going to use the array_slice() function which returns a sequence of elements from the array, defined by the offset and length parameters. By slicing the array from the beginning to the second-to-last element, we effectively remove the last element. Example: Removing an element from the end of the array using array_slice() function in PHP.
Output Original array: 1, 2, 3, 4, 5 Modified array: 1, 2, 3, 4 |
Reffered: https://www.geeksforgeeks.org
PHP |
Type: | Geek |
Category: | Coding |
Sub Category: | Tutorial |
Uploaded by: | Admin |
Views: | 24 |