Home >Backend Development >PHP Problem >How to remove the largest and smallest elements from a php array
Removal method: 1. Use "sort($arr)" to sort the array in ascending order. After sorting, the first element of the array is the minimum value, and the last element is the maximum value; 2. Use "array_pop" ($arr)" to delete the last element, and "array_shift($arr)" to delete the first element.
The operating environment of this tutorial: windows7 system, PHP7.1 version, DELL G3 computer
Remove the largest php array and the method of the smallest element
Step 1. Use sort() to sort the array in ascending order
<?php header("Content-type:text/html;charset=utf-8"); $arr=array(52,1,45,9,0,21,-1,40,-5); sort($arr); var_dump($arr); ?>
It can be seen that the first element of the array after sorting is the minimum value, and the last element is the maximum value. Just delete these two values.
Step 2. Delete the maximum value and minimum value (the first element and the last element of the array)
So how to delete the first element and the last element of the array Well, you can use the array_pop() and array_shift() functions
array_pop(): delete the last element in the array (pop it off the stack).
array_shift(): Delete the first element in the array.
array_pop($arr); //去掉最大值 var_dump($arr);
array_shift($arr); //去掉最小值 var_dump($arr);
Note: The array_pop() and array_shift() functions will modify the original array.
Recommended learning: "PHP Video Tutorial"
The above is the detailed content of How to remove the largest and smallest elements from a php array. For more information, please follow other related articles on the PHP Chinese website!