Friday, 21st February 2020
Programming

Find the largest three elements in an array

Written by     on    02 Jan, 2020     0      

PHP Get Highest Value from Array

See the code below for more understanding.

Examples : 1

<pre>
//Simpliest way should be something like that :

$number_1 = array(10,12,14,18,12,15,88,19, 786, 20);

rsort($number_1); // order array desc

// Just echo first 3 result in your array
echo $number_1[0];
echo $number_1[1];
echo $number_1[2];
</pre>

Output

<pre>
Top three elements are: 786, 88, 20
</pre>

Examples : 2

Given an array of integers, write an algorithm to find the first three largest elements in the array

<pre>
$number = array(10,12,14,18,12,15,88,19, 786, 20);
$biggest_number_1 = $biggest_number_2= $biggest_number_3 = 0;
for ($i = 0; $i < count($number) ; $i++)
{
	if ($number[$i] > $biggest_number_3)
	{
		$biggest_number_1 = $biggest_number_2;
		$biggest_number_2 = $biggest_number_3 ;
		$biggest_number_3  = $number[$i];
	}
	else if ($number[$i] > $biggest_number_2)
	{
		$biggest_number_1 = $biggest_number_2;
		$biggest_number_2 = $number[$i];
	}
	else if ($number[$i] > $biggest_number_1){
		$biggest_number_1 = $number[$i];
	}
}
echo $biggest_number_1;
echo $biggest_number_2;
echo $biggest_number_3;
</pre>

Output

<pre>
Top three elements are: 786, 88, 20
</pre>
Tags :  arrayFind first three largest elements in a given arrayorder array descPHP

Write a Reply or Comment

Your email address will not be published. Required fields are marked *

Submit Guest Post Content
Are you a passionate writer or expert in our categories? You can submit content on our website. Before writing content, you should read our guest posting guidelines.
Read More
NEVER MISS A POST
Get the latest posts and awesome deals delivered to your inbox for free. 100% Privacy.