0

I want to know How I can get first and second larger decimal no. in array in PHP. Like :

$a = 0.24;
$b = 0.45;
$c = 0.50;
$d = 0.30;

$large = array($a,$b,$c,$d);

How I can do this, Or Which function I need to use ?

Thanks !

Kunwar Siddharth Singh
  • 1,676
  • 6
  • 33
  • 66

5 Answers5

0

try this .... number_format with your variable

$large = array(number_format($a,2),number_format($b,2),number_format($c,2),number_format($d,2));
Zeeshan
  • 1,659
  • 13
  • 17
0

you can use max($array);

$large = array($a,$b,$c,$d);
$result = max($large);

var_dump($result);

This gives:

float 0.5

To get the first and second largest elements you need to sort the array. asort sorts the array in ascending order of the values. The first and the second largest numbers are the two numbers at the rightmost end of the array. array_pop removes the element at the end of the array. The first array_pop removes the largest and second array_pop removes the second largest.

like

 $large = array($a,$b,$c,$d);

asort($large);

$largest = array_pop($large);

$second_largest = array_pop($large);

echo "largest = ".$largest;

echo "second_largest = ".$second_largest;

This gives:

largest = 0.5
second_largest = 0.45
Shikhar Subedi
  • 606
  • 1
  • 9
  • 26
0

I am not clear about your requirement.If you need get larger decimal no. in array or largest number from all the multiple array? If you need to get max value from each array you can use max function. max() returns the numerically highest of the parameter values. If multiple values can be considered of the same size, the one that is listed first will be returned.

When max() is given multiple arrays, the longest array is returned. If all the arrays have the same length, max() will use lexicographic ordering to find the return value.

When given a string it will be cast as an integer when comparing.

Damodaran
  • 10,882
  • 10
  • 60
  • 81
0

you can try this ...

$large = array($a,$b,$c,$d);
rsort($large);
print_r($large);

Applicable sort functions:

sort
rsort
asort
arsort
natsort
natcasesort
ksort
krsort

You can also see this link

How can I sort arrays and data in PHP?

this is very helpful for all of us

Community
  • 1
  • 1
Siraj Khan
  • 2,328
  • 17
  • 18
0

If you're wanting to retrieve the first and second largest values from an array, just use rsort():

$numbers = array(0.90, 0.30, 0.20, 0.50);
rsort($numbers);

$numbers will now contain an array sorted from highest to lowest, and you will be able to access the values like this:

$highest = $numbers[0];
$secondHighest = $numbers[1];
Jack Greenhill
  • 10,240
  • 12
  • 38
  • 70