2

I am trying to order an array produced by a foreach loop, here is my code:

$lowestvar = array();

foreach ($variations as $variation){
    $lowestvar[] = $variation['price_html'];            
}

I am then using array_multisort like this:

array_multisort($lowestvar, SORT_ASC);
print_r($lowestvar);

This works for the first looped item with a output of:

Array ( [0] => £10.00 [1] => £15.00 ) 

But the second array in the loop looks like this:

Array ( [0] => £10.00 [1] => £5.00 ) 

Any ideas on where i am going wrong?

2
  • Please edit your question to include the output of the following statement: echo '<pre>'.print_r($variations, 1).'</pre>';. Commented Apr 8, 2014 at 15:46
  • That produces a lot of code, and the majority of it is pointless to show. Commented Apr 8, 2014 at 15:49

2 Answers 2

4

You're sorting STRINGS, which means that 10 < 5 is true. Remember that string sorting go char-by-char, not by "entire value".

Sign up to request clarification or add additional context in comments.

3 Comments

Don't let that happen again. Coffee before stack. ALWAYS.
So is there away around this?
usort(), with a callback that converts your strings to numbers for comparison purposes. But if you're getting those money values from somewhere where they are JUST numbers, then you should be storing those plain numbers. Formatted strings should only be generated at output time, never for intermediate stages liket his.
2

You can use usort() as like in the following example

 function cmp($a1, $b1)
 {
  $a=str_replace('£','',$a1);
  $b=str_replace('£','',$b1);
  if ($a == $b) {
      return 0;
    }
   return ($a < $b) ? -1 : 1;
 }

  $a = array('£10.00','£5.00');

  usort($a, "cmp");
  print_r($a);

Output

Array
(
  [0] => £5.00
  [1] => £10.00
 )

2 Comments

not need also to int typecasting... I hate php for this))
some explain: how can I guarantee that my strings sorted correctly, if sometimes they compared as numbers?

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.