0

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.

2 Answers 2

2

Don't compare strings then, compare numbers:

return $a->cost_per_blog - $b->cost_per_blog;
Sign up to request clarification or add additional context in comments.

Comments

1

You compare them as strings not as doubles.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.