How to delete the maximum value from a php array

青灯夜游
Release: 2023-03-16 07:26:01
Original
2267 people have browsed it

Two methods: 1. Traverse the array and use unset() to delete the largest element. The syntax "foreach($a as $k=>$v){if($v==max($a )){unset($a[$k]);}}". 2. Use the "sort($a);array_pop($a);" statement to delete.

How to delete the maximum value from a php array

The operating environment of this tutorial: windows7 system, PHP8.1 version, DELL G3 computer

php array delete maximum Two methods of value

1. Traverse the array and use unset() to delete the largest element

  • Use foreach Traverse the array

  • In the loop body, find the element with the maximum value

  • Use unset() to delete the element

<?php
header("Content-type:text/html;charset=utf-8");
$arr=array(1,45,9,52,0,-5,21,-1,40);
var_dump($arr);
$max=max($arr);
echo "最大值为:".$max;
foreach($arr as $k=>$v){
	if($v==$max){
		unset($arr[$k]);
	}
}
echo "<br><br>删除最大值后:";
var_dump($arr);
?>
Copy after login

How to delete the maximum value from a php array

2. Sort the array in ascending order and use array_pop() to delete the largest element

  • Use sort() sorts the array in ascending order

  • After sorting, the last element of the array is the maximum value, just use array_pop() to delete it.

    array_pop(): Delete the last element in the array.

<?php
header("Content-type:text/html;charset=utf-8");
$arr=array(1,45,9,52,0,-5,21,-1,40);
var_dump($arr);
sort($arr);
var_dump($arr);
array_pop($arr);        //去掉最大值
var_dump($arr);
?>
Copy after login

How to delete the maximum value from a php array

Recommended learning: "PHP Video Tutorial"

The above is the detailed content of How to delete the maximum value 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