Home > Enterprise >  Return the indices of the largest second largest values in a PHP array?
Return the indices of the largest second largest values in a PHP array?

Time:08-14

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:

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) }

CodePudding user response:

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
  • Related