


PHP array learning: Compare array elements and obtain the first and second largest values
In the previous article, we introduced the method of using the bubble algorithm to sort the array elements in ascending order. If you are interested, you can click on the link to read → "PHP Array Learning: Using the Bubble Algorithm to Sort the Elements in Ascending Order ! 》. This time we continue the PHP array learning series and introduce the method of comparing array elements and obtaining the first and second largest values.
The theme of this article is: "Given a set of numbers, calculate its maximum and second maximum values".
Implementation idea: Use an array to wrap this set of numbers, so this will involve comparing the size of the array elements
Set two variables$max
and $secMax
are used to store the maximum value and the second maximum value obtained. However, you need to assign initial values to everyone first, assigning the first element and the second element of the array to them. But make sure $max
is larger than $secMax
, so you have to make a judgment
if ($arr[0] > $arr[1]){//这个if是为了防止出现数组第一个值就是最大值 $secMax = $arr[1]; } else if ($arr[0] < $arr[1]){ $max = $arr[1]; }
and then use a for loop to continuously traverse the $arr array. [If you don’t understand, you can read the article "PHP Loop Learning 3: How to use for loop statements to traverse arrays"]
for ($i = 0;$i< count($arr);$i++){ //循环数组 //循环体 }
In the loop body, continue to $max
, $secMax
is compared with each value of the array ($arr[$i]
):
if
$arr[$ i]
is greater than$max
, then assign the$max
value to$secMax
, and$arr[$i]
Assign to$max
,
if ($arr[$i] > $max){ $secMax = $max; $max = $arr[$i]; }
and if
$arr[$i]
is less than$ max
, but$arr[$i]
is greater than$secMax
, then only$secMax
and$arr[$i] are exchanged
, copy$arr[$i]
to$secMax
.
if ($arr[$i] < $max && $arr[$i] > $secMax){ $secMax = $arr[$i]; }
By continuing to compare like this, you can ensure that $max stores the maximum value of the array, and $secMax stores the second largest value of the array.
Let’s take a look at the complete implementation code:
function takeNum($arr){ //定义了两个变量$max和$secMax来存放最大和第二大的数值 $max = $arr[0]; $secMax = $arr[0]; if ($arr[0] > $arr[1]){//这个if是为了防止出现数组第一个值就是最大值 $secMax = $arr[1]; } else if ($arr[0] < $arr[1]){ $max = $arr[1]; } for ($i = 0;$i< count($arr);$i++){//循环数组 if ($arr[$i] > $max){ $secMax = $max; $max = $arr[$i]; } else if ($arr[$i] < $max && $arr[$i] > $secMax){ $secMax = $arr[$i]; } } echo "最大值为".$max.",第二大值为".$secMax; }
Test it: define the following array, call the takeNum($arr) function to see the output
$arr = array(555,5,1,429,18,21,52,2,52,9,3,); takeNum($arr);
It can be seen that the first largest value is 555 and the second largest value is 429; see if the output result is this:
OK, the output result is correct .
Next let’s talk about the knowledge points used. There is no need to say more about loops (you can read the article "PHP Loop Learning Series Summary"), let’s give you a brief introduction if else statement.
The if else statement is a type of execution based on conditional judgment in process control. When this statement is executed, the condition is first judged, and then the corresponding operation is made based on the judgment result. It can be subdivided into three types, namely if statement, if...else statement, if...else if...else statement.
The syntax of if statement:
if (判断条件) { 语句块; }
if...else The syntax of statement:
if (判断条件) { 语句块 1; } else { 语句块 2; }
if...else The syntax of if...else statement:
if (判断条件 1) { 语句块 1; } else if (判断条件 2) { 语句块 2; } else if (判断条件 3) { 语句块 3; } ......
Okay, that’s all. If you want to know anything else, you can click this. → →php video tutorial
Finally, I would like to recommend a free video tutorial on PHP arrays: PHP function array array function video explanation, come and learn!
The above is the detailed content of PHP array learning: Compare array elements and obtain the first and second largest values. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.
