37

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. The sorting algorithm should respect float values and maintaining index association.

0

4 Answers 4

67

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
)
Sign up to request clarification or add additional context in comments.

Comments

18

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 ) 

Comments

1

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

Comments

1

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

1 Comment

As demonstrated by the other answers, the data preparation step is not necessary.

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.