-6

Below is a php variable numbers which contains an array i need to sort in Ascending order and result which i want is below that. Please help. $numbers = array(3.11,1, 2, 3.1,3.10,3,3.2,3.3);

result i want:

1 2 3 3.1 3.2 3.3 3.10 3.11

3 Answers3

1

If you setup your array with strings, you can use natsort function to get result you want

$numbers = array('1', '2', '3', '3.1', '3.2', '3.3', '3.10', '3.11');
natsort($numbers);
print_r($numbers); 

Now, when you init array with numbers, there is no difference between 3.10 and 3.1

demo

splash58
  • 26,043
  • 3
  • 22
  • 34
0

You can use sort() function

$numbers = array(1, 2, 3, 3.1, 3.2, 3.3, 3.10, 3.11);
sort($numbers);
var_dump($numbers);
Ahsan Ali
  • 4,951
  • 2
  • 17
  • 27
  • i tried it but the result which i am getting is 1, 2, 3, 3.10, 3.1, 3.11, 3.2, 3.3 but what i want is 1, 2, 3, 3.1, 3.2, 3.3, 3.10, 3.11 – Karan Tiwari Dec 20 '17 at 06:30
  • sorry i asked wrong question now i have corrected the question please check my array order is different. – Karan Tiwari Dec 20 '17 at 06:44
-1

You just need to use sort() function.

For e.g.

$numbers = array(1, 2, 3, 3.1, 3.2, 3.3, 3.10, 3.11);
sort($numbers);
print_r($numbers);

Output: 1 2 3 3.1 3.2 3.3 3.10 3.11

  • sorry i asked wrong question now i have corrected the question please check my array order is different. – Karan Tiwari Dec 20 '17 at 06:44
  • Your float number have unequal decimal points, you need to keep all float values in same decimal point. eg. php doesn't consider trailing 0's in decimal point, you have to make your 3.1 to 3.01, 3.2 to 3.02 likewise. Then use sort you'll get your answer. – Sandesh Mule Dec 20 '17 at 11:23