I have an array like this:
$numbers = [20, 2, 248, 992, 42]
I want to calculate the difference between the highest
and lowest
numeral. For instance of 248
it should be 8 - 2 = 6
(highest is 8, lowest is 2). Another example: 992 = 9 -2 = 7
(again, highest - lowest).
As a result, I want to output the input-array in the correct order, according to the difference in the math described above.
To give a complete example:
Input-Array: $numbers = [20, 2, 248, 992, 42]
Math:
20 = 2 - 0 = 2 *
2 = 2 - 2 = 0
248 = 8 - 2 = 6
992 = 9 - 2 = 7
42 = 4 - 2 = 2 *
Output-Array: 2, 42, 20, 248, 992
(Since the 42 is behind the 20 in the input-array, this number should come first in the sorting.
I tried the following so far:
function digitDifferenceSort($a) {
$out = array();
foreach($a as $z) {
$number = str_split($z);
sort($number);
// substract the biggest minus the smallest
$diff = $number[max(array_keys($number))] - $number[0];
$out[] = $diff;
}
// format again
asort($out);
// iterate through the reordered out-array and get the values
$reorderedArray = array();
foreach($out as $k => $reordered) {
$reorderedArray[] = $a[$k];
}
}
This works "so far, so good", but is struggling with the problem I described above, if the same difference comes again. Maybe asort()
isn't the right thing to do here? Maybe usort would be the right approach?