Search code examples
phparraysarray-multisort

php array sort in foreach


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?


Solution

  • 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
     )