Daniel Benzie
Daniel Benzie

Reputation: 479

Sorting array by values PHP

I am sorting through an array using the usort function. The loop is working correctly as is the sorting (to some degree) however I seem to have missed something with regards to decimal places etc. My function is below

usort($this->view->blogs, 'comparison');

And here is the function. The function call works correctly and I can see I am returned sorted data

function comparison($a, $b)
{
    return strcmp($a->cost_per_blog, $b->cost_per_blog);
}

The issue is with the actual sorting logic for instance I am returned a list like below

0.09724
0.58344
1.16688
12.05776
120.5776
126.60648
13.22464
132.63536
138.66424
168.80864
18.08664
18.08664
18.67008
180.8664
19.25352
21.10108
22.26796

the pattern continues... It appears that I am not taking into account the sorting of 3 digit numbers. I cant seem to think of what I am missing. Any help would be greatly appreciated.

Upvotes: 0

Views: 122

Answers (2)

Razvan
Razvan

Reputation: 10093

You compare them as strings not as doubles.

Upvotes: 1

deceze
deceze

Reputation: 522451

Don't compare strings then, compare numbers:

return $a->cost_per_blog - $b->cost_per_blog;

Upvotes: 2

Related Questions