Home » Php » sort numeric string array in php

sort numeric string array in php

Posted by: admin April 23, 2020 Leave a comment

Questions:

I have a php array like :

myarr[1] = "1",
myarr[2] = "1.233",
myarr[3] = "0",
myarr[4] = "2.5"

the values are actually strings but i want this array to be sorted numerically, also considering float values and maintaining index association.

Please help me out.
Thanks

How to&Answers:

You can use the normal sort function. It takes a second parameter to tell how you want to sort it. Choose SORT_NUMERIC.

Example:

  sort($myarr, SORT_NUMERIC); 
  print_r($myarr);

prints

Array
(
    [0] => 0
    [1] => 1
    [2] => 1.233
    [3] => 2.5
)

Update: For maintaining key-value pairs, use asort (takes the same arguments), example output:

Array
(
    [3] => 0
    [1] => 1
    [2] => 1.233
    [4] => 2.5
)

Answer:

Use natsort()

$myarr[1] = "1";
$myarr[2] = "1.233";
$myarr[3] = "0";
$myarr[4] = "2.5";

natsort($myarr);
print_r($myarr);

Output:

Array ( [2] => 0 [0] => 1 [1] => 1.233 [3] => 2.5 ) 

Answer:

Use the php usort function and in your callback function convert your strings to floats to compare them.

Answer:

You can convert your strings to real numbers (floats) and sort them afterwards:

foreach ($yourArray as $key => $value) {
    $yourArray[$key] = floatval($value);
}

sort($yourArray, SORT_NUMERIC);