Backend Development
PHP Tutorial
PHP array learning: Compare array elements and obtain the first and second largest valuesPHP 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$maxvalue 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$secMaxand$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!
PHP's Purpose: Building Dynamic WebsitesApr 15, 2025 am 12:18 AMPHP is used to build dynamic websites, and its core functions include: 1. Generate dynamic content and generate web pages in real time by connecting with the database; 2. Process user interaction and form submissions, verify inputs and respond to operations; 3. Manage sessions and user authentication to provide a personalized experience; 4. Optimize performance and follow best practices to improve website efficiency and security.
PHP: Handling Databases and Server-Side LogicApr 15, 2025 am 12:15 AMPHP uses MySQLi and PDO extensions to interact in database operations and server-side logic processing, and processes server-side logic through functions such as session management. 1) Use MySQLi or PDO to connect to the database and execute SQL queries. 2) Handle HTTP requests and user status through session management and other functions. 3) Use transactions to ensure the atomicity of database operations. 4) Prevent SQL injection, use exception handling and closing connections for debugging. 5) Optimize performance through indexing and cache, write highly readable code and perform error handling.
How do you prevent SQL Injection in PHP? (Prepared statements, PDO)Apr 15, 2025 am 12:15 AMUsing preprocessing statements and PDO in PHP can effectively prevent SQL injection attacks. 1) Use PDO to connect to the database and set the error mode. 2) Create preprocessing statements through the prepare method and pass data using placeholders and execute methods. 3) Process query results and ensure the security and performance of the code.
PHP and Python: Code Examples and ComparisonApr 15, 2025 am 12:07 AMPHP and Python have their own advantages and disadvantages, and the choice depends on project needs and personal preferences. 1.PHP is suitable for rapid development and maintenance of large-scale web applications. 2. Python dominates the field of data science and machine learning.
PHP in Action: Real-World Examples and ApplicationsApr 14, 2025 am 12:19 AMPHP 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.
PHP: Creating Interactive Web Content with EaseApr 14, 2025 am 12:15 AMPHP makes it easy to create interactive web content. 1) Dynamically generate content by embedding HTML and display it in real time based on user input or database data. 2) Process form submission and generate dynamic output to ensure that htmlspecialchars is used to prevent XSS. 3) Use MySQL to create a user registration system, and use password_hash and preprocessing statements to enhance security. Mastering these techniques will improve the efficiency of web development.
PHP and Python: Comparing Two Popular Programming LanguagesApr 14, 2025 am 12:13 AMPHP 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.
The Enduring Relevance of PHP: Is It Still Alive?Apr 14, 2025 am 12:12 AMPHP is still dynamic and still occupies an important position in the field of modern programming. 1) PHP's simplicity and powerful community support make it widely used in web development; 2) Its flexibility and stability make it outstanding in handling web forms, database operations and file processing; 3) PHP is constantly evolving and optimizing, suitable for beginners and experienced developers.


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

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

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

Atom editor mac version download
The most popular open source editor

Dreamweaver CS6
Visual web development tools

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function





