PHP is a popular server-side scripting language that is widely used in the development of websites and web applications. Arrays in PHP are a commonly used data structure that allow you to store and manipulate multiple values. In some cases, you may need to remove an element from the beginning or end of an array. This article will show you how to delete the first and last element of an array using PHP.
Delete the first element of the array
To delete the first element of the array, you can use the array_shift() function in PHP. This function will remove the first element from the array and will return the value of the removed element. If the array is empty, NULL is returned.
The following is an example that demonstrates how to use the array_shift() function to delete the first element from an array:
<?php $fruits = array("apple", "banana", "cherry"); echo "Original array: "; print_r($fruits); $removed_fruit = array_shift($fruits); echo "Removed fruit: " . $removed_fruit . "\n"; echo "Updated array: "; print_r($fruits); ?>
In the above example, we first define an array containing three fruit names array. We then remove the first element (i.e. "apple") using the array_shift() function and save it to the variable $removed_fruit. Finally, we print the updated array, which only contains the two fruits "banana" and "cherry".
Delete the last element of the array
To delete the last element of the array, you can use the array_pop() function in PHP. This function will remove the last element from the array and will return the value of the removed element. If the array is empty, NULL is returned.
Here is an example that demonstrates how to use the array_pop() function to remove the last element from an array:
<?php $fruits = array("apple", "banana", "cherry"); echo "Original array: "; print_r($fruits); $removed_fruit = array_pop($fruits); echo "Removed fruit: " . $removed_fruit . "\n"; echo "Updated array: "; print_r($fruits); ?>
In the above example, we first define an array containing three fruit names. array. We then remove the last element (i.e. "cherry") using the array_pop() function and save it to the variable $removed_fruit. Finally, we print the updated array, which only contains the two fruits "apple" and "banana".
Conclusion
In PHP, deleting the first and last elements of an array is relatively simple. You just need to use array_shift() or array_pop() function. These functions both delete elements and return the value of the deleted element. Understanding these functions can help you handle array operations more efficiently.
The above is the detailed content of How to delete the head and tail of a php array. For more information, please follow other related articles on the PHP Chinese website!