Ahh, good to be back after the holidays. Took a little time off from most the blogs including this one for those who are new readers.

In the meantime a good question came in on the sorting post back in October from Beregszászi Mihály, who wrote:

I have got a problem:
rsort($numbers);

Print:
9
8
7
70
6
69
68
67

This is my problem! My dream:
70
69
68
67
66
65
9
8
7
6

The first thing I did was whip up some example code to test the rsort() and asort() functions. I didn’t find the situation that he was talking about so I tried to work it backwards and treat the numbers as strings with spaces and possibly returns and other hidden characters in them.

This created the following sort bug that Beregszászi was talking about (and yet he didn’t offer the code for):

[code=”html”]
Reverse sort -> rsort()
9,8 ,70 ,7 ,69 ,68,67,6
[/code]

Solution
What Beregszászi is looking for is a numerical sort using data that isn’t in numerical type. To change the type this is called casting. PHP isn’t as anal as some most languages about using the right type but it is critical in some most other languages. It’s best to get in the habit as a programmer as always ensuring the data type matches or you’ll end up with type mismatch errors (in PHP you’ll often end up with unexpected results).

First we need to type the data as a number so we can sort it properly. We can do that as follows:

<?php
$numbers2 = array(
‘9′,
‘8            ‘,
‘7  ‘,
‘70
,
‘6′,
‘69

‘,
‘68′,
‘67′);

print “<hr>Jumbled order (STRING TEST)<br />”;
print(join(“,”,$numbers2));

// begin code to cast array contents from string to numeric
$sizeof = count($numbers2);
for($i=0;$i< $sizeof;$i++){
        $numbers2[$i] = (int)$numbers2[$i];     
}
// end code to cast array contents from string to numeric

print “<br />Jumbled order (STRING TEST after casting)<br />”;
print(join(“,”,$numbers2));

rsort($numbers2);
print “<br />Reverse sort -> rsort()<br /> “ . (join(“,”,$numbers2));
print “<br />Regular order -> asort()<br />”;
asort($numbers2);
print(join(“,”,$numbers2));
?>

Now it will sort as the “dream” option he requested.