During the PHP development process, it is often necessary to perform some operations on arrays, and removing the last value of the array is also one of the common operations. Below, this article will introduce some methods to achieve this operation.
Method 1: Use the array_pop function
The array_pop function can remove the last value of the array and return that value. For example:
$arr = array('apple','banana','orange'); $last_value = array_pop($arr); print_r($arr); echo '去除的值为:' . $last_value;
The output result is:
Array ( [0] => apple [1] => banana ) 去除的值为:orange
This method is very simple and can be implemented directly using the array_pop function. However, it should be noted that this method will directly modify the original array.
Method 2: Use the array_slice function
The array_slice function can return a part of the array. For example, we can use this function to get the array except the last element. For example:
$arr = array('apple','banana','orange'); $new_arr = array_slice($arr, 0, -1); print_r($new_arr);
The output result is:
Array ( [0] => apple [1] => banana )
This method will not modify the original array, but it should be noted that this method will generate a new array.
Method 3: Use the unset function
The unset function can delete one or more elements specified in the array. We can use this function to delete the last element. For example:
$arr = array('apple','banana','orange'); unset($arr[count($arr)-1]); print_r($arr);
The output result is:
Array ( [0] => apple [1] => banana )
This method will not generate a new array, but it should be noted that this method will directly modify the original array.
To sum up, we can use the above three methods to achieve the operation of removing the last value of the array. Each method has its advantages and disadvantages. You need to choose the method that suits you according to your specific actual needs.
The above is the detailed content of php remove last value from array. For more information, please follow other related articles on the PHP Chinese website!