Home  >  Article  >  Backend Development  >  How to find the sum of the two largest numbers in an array in php

How to find the sum of the two largest numbers in an array in php

DDD
DDDOriginal
2023-06-01 11:56:49798browse

php method to find the array and the two largest numbers: 1. Create a PHP sample file, 2. Store the data in the array through the "$arr=array" syntax, 3. Use "rsort() " function to sort in descending order. 4. Define the first element of the array as "$arr[0]" and the second element of the array as "$arr[1]". Through "$res=$arr[0] $arr[ 1];" syntax implements array addition; 5. Output the result through "echo".

How to find the sum of the two largest numbers in an array in php

The operating environment of this tutorial: windows10 system, PHP8.1.3 version, DELL G3 computer

php finds the sum of the two largest arrays Number method:

In PHP, if you want to find the two maximum values ​​in a set of data and add the two maximum values ​​to the sum, you can use an array.

You only need to store the data into the array, and then sort the array in descending order, so that the first element and the second element of the array are the two maximum values, and you can add them together.

1. Store the data in the array

$arr=array(3,9,32,4,1,12,45,8);

2. Use the rsort() function to sort in descending order

rsort () function can sort a numerical array in descending order.

How to find the sum of the two largest numbers in an array in php

It can be seen that the first element and the second element of the array are the two maximum values. You only need to use the array subscript to take them out.

$arr[0] //数组第一个元素
$arr[0] //数组第二个元素

3. Add the first element and the second element x

$res=$arr[0]+$arr[1];
echo "两个最大值相加:".$arr[0]." + ".$arr[1]." = ".$res;

How to find the sum of the two largest numbers in an array in php

The above is the detailed content of How to find the sum of the two largest numbers in an array in php. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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