How PHP compares array elements and finds the maximum value
This article will explain in detail how PHP compares array elements and finds the maximum value. The editor thinks it is very practical, so I share it with you as a reference. I hope you can get something after reading this article.
1. Set two variables, $max and $secMax, to store the maximum and second largest values obtained.
But you need to assign initial values to everyone first, and assign the first and second elements of the array to them. But make sure that $max is bigger than $secMax, so make a judgment.
If ($arr [0] > $arr [1]) {/ / this if is to prevent the occurrence of the array where the first value is the maximum $secMax = $arr [1];} else if ($arr [0])
< $arr[1]){ $max = $arr[1]; } 2、使用for循环,不断遍历$arr数组。 for ($i = 0;$i< count($arr);$i++){ //循环数组 //循环体 } 3、在循环体中,不断将$max、$secMax与数组每个值($arr[$i])比较。 如果$arr[$i]比$max大,则将$max值赋给$secMax,把$arr[$i]赋给$max。 if ($arr[$i] >$max) {$secMax = $max; $max = $arr [$I];}
If $arr [$I] is less than $max, but $arr [$I] is greater than $secMax, only the values between $secMax and $arr [$I] are exchanged, and $arr [$I] is copied to $secMax.
If ($arr [$I]
< $max && $arr[$i] >$secMax) {$secMax = $arr [$I];}
This constant comparison ensures that $max holds the maximum value of the array, and $secMax holds the second largest value of the array.
This is the end of the article on "how to compare array elements and find the most value in PHP". I hope the above content can be of some help to you, so that you can learn more knowledge. if you think the article is good, please share it for more people to see.