-1

we are trying to reorder the number for example

        5695479  to 9976554
        48932  to 98432

means all bigger numbers then smaller number. i was searching for some inbuilt function in php, we found sort function can do with array.

$numbers=array(4,6,2,22,11);
sort($numbers);


function my_sort($a,$b)
{
if ($a==$b) return 0;
return ($a<$b)?-1:1;
}

$a=array(4,2,8,6);
usort($a,"my_sort");

i have searched lot but i could not found any inbuilt functions.

sujara
  • 29
  • 5
  • I don't think you will find anything built into php which will do a very specialized odd-sorting like that. You will have to create your own code to deal with the different situations for which to sort what is in the array (a conditional to check if its within a certain range, then sort/add/rebuild the array based on it). – IncredibleHat Aug 08 '20 at 12:25

1 Answers1

2

There is no specific in-built function for this. However, you can use more than 1 inbuilt function to accomplish your task.

  • You can convert the integer to string usingstrval.
  • Now, split the string by each digit to get an array of integers.
  • Apply rsort() to sort them in descending order.
  • Implode() them back to get the number you desire.

Snippet:

<?php

$str = strval(5695479);
$nums = str_split($str);
rsort($nums);
echo implode("",$nums);

Another alterantive is to use counting sort for digits. Since digits will always be between 0-9, collect their count and loop from 9 to 0 and get the new number. This method would be faster than the first method if you have the number in string format with huge lengths.

Snippet:

<?php

$num = 48932; // if number is in string format, loop char by char using for loop
$count = [];

while($num > 0){
     if(!isset($count[$num % 10])) $count[$num % 10] = 0;
    $count[$num % 10]++;
    $num = intval($num / 10);
}

$new_num = 0;
for($i = 9; $i >=0; --$i){
  if(!isset($count[$i])) continue;
  while($count[$i]-- > 0) $new_num = $new_num * 10 + $i; // you would rather concatenate here incase of string. 
}

echo $new_num;
nice_dev
  • 17,053
  • 2
  • 21
  • 35