0

I need to output the numbers by order of their sums.

    <?php
    $str = '11 11 2004 6 99 43 88 10003';
    function orderWeight($str) {
        $nums = explode(" ", $str);
        $newArray= [];
        foreach($nums as $key => $value){
            $key = array_sum(str_split($value));
            if(array_key_exists($key,$newArray)){
                $key = $key + 0.5;

                $newArray += array($key => $value);
            }else{

                $newArray += array($key => $value);
            }

        }
        ksort($newArray);
        $ans = implode(' ',$newArray);
        print_r($ans);
    }
    echo(orderWeight($str));

The result is

11 10003 2004 43 88 99

It is sorted correctly but some numbers are overwritten by the keys that match by the sum.

Don't Panic
  • 41,125
  • 10
  • 61
  • 80

1 Answers1

0

Floats in keys of array in PHP are truncated to integer. So you get duplicate keys for 2 and 2.5 (both truncate to 2). You need to use string keys instead and then use custom function to compare.

Also you need to change if with while (you can have more than 2 duplicate values within input string).

Here is code that should works:

<?php
$str = '11 11 2004 6 99 43 88 10003';
function orderWeight($str) {
    $nums = explode(" ", $str);
    $newArray = [];
    foreach ($nums as $key => $value) {
        $key = array_sum(str_split($value));
        while (array_key_exists((string)$key, $newArray)) {
            $key = $key + 0.001;
        }
        $newArray += [(string)$key => $value];
    }
    uksort($newArray, function ($a, $b) {return $a - $b;});
    $ans = implode(' ', $newArray);
    return $ans;
}
echo orderWeight($str);
Andrey Yerokhin
  • 273
  • 1
  • 7