Home > Backend Development > PHP Problem > How to remove the largest and smallest elements from a php array

How to remove the largest and smallest elements from a php array

青灯夜游
Release: 2023-03-16 06:20:01
Original
2421 people have browsed it

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.

How to remove the largest and smallest elements from a php array

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);
?>
Copy after login

How to remove the largest and smallest elements from a php array

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);
Copy after login

How to remove the largest and smallest elements from a php array

array_shift($arr);       //去掉最小值
var_dump($arr);
Copy after login

How to remove the largest and smallest elements from a php array

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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template