Search code examples
phpranking

how to rank array's index in PHP


I need rank in my system. I have an array $arr = array(120,26,38,96,22);. I need to rank the index inside without changing their position.

The output I need is something like:

120 is rank 1, 26 is rank 4, 38 is rank 3, 96 is rank 2, 22 is rank 5

I've tried this, but all ranked as rank 1:

<?php
$arr = array(120,26,38,96,22);
$rank = 0;
$score=false;
$rows = 0;

foreach($arr as $sort){
    $rows++;
    if($score != $arr){
        $score = $arr;
        $rank = $rows;
    }echo $sort.' is rank '.$rank.'</br>';  
}
?>

And also I need the array length to be dynamic.


Solution

  • Here's one way:

    $arr  = array(120,26,38,96,22);
    $rank = $arr;
    rsort($rank);
    
    foreach($arr as $sort) {
        echo $sort. ' is rank ' . (array_search($sort, $rank) + 1) . '</br>';
    }
    
    • Copy the original array as $rank and sort in reverse so the keys will be the rank -1
    • Loop the original array and search for that value in $rank returning the key (rank)
    • Add 1 since keys start at 0

    Or another possibility:

    $arr  = array(120,26,38,96,22);
    $rank = $arr;
    rsort($rank);
    $rank = array_flip($rank);
    
    foreach($arr as $sort) {
        echo $sort . ' is rank '. ($rank[$sort] + 1) . '</br>';
    }
    
    • Copy the original array as $rank and sort in reverse so the keys will be the rank -1
    • Flip the $rank array to get values as keys and rank as values
    • Loop the original array and use the value as the $rank key to get the rank
    • Add 1 since keys start at 0