Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Return the indices of the largest + second largest values in a PHP array?

Goal: given a string containing a list of comma-separated float values, return the indices of the largest and second largest floats

  • "Largest" and "Second largest" should be sorted numerically (not as strings); e.g., "100" is larger than "2"

Example:

  • given a string: "11,2,1,100,1.5"
  • return the indices: 3 and 0 (corresponding to numeric values 100 and 11)

What I’ve tried:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

New to PHP, but I feel like I’m so close with the following code, but can’t figure out how to get the actual index values:

$x_string = "11,2,1,100,1.5";
$x_array = explode(",", $x_string);

// apply floatval to every element of array
function float_alter(&$item) { $item = floatval($item); }
array_walk($x_array, float_alter);

$temp = $x_array;
arsort($temp);

var_dump($temp);

Outputs:

array(5) { [3]=> float(100) [0]=> float(11) [1]=> float(2) [4]=> float(1.5) [2]=> float(1) }

>Solution :

You can split and floatval in one step. Then sort descending to have largest first. The keys are still kept.

$string = "11,2,1,100,1.5";
$floats = array_map('floatval', explode(',', $string));
arsort($floats, SORT_NUMERIC | SORT_DESC);

print_r($floats);

list($largestKey, $secondLargestKey) = array_keys($floats);
echo "$largestKey, $secondLargestKey";

prints

Array
(
    [3] => 100
    [0] => 11
    [1] => 2
    [4] => 1.5
    [2] => 1
)
3, 0
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading