1

I'm trying to sort an array of strings numerically in php. Each string beginns with a number.

The content of the array looks like this:

1_some-str
2_some-str
3_some-str
4_some-str
...
10_some-str
11_some-str

With sort() the output is like this:

10_some-str
11_some-str
1_some-str
2_some-str
...    
9_some-str

How can I achive, that the array gets sorted upwards from from 1-11?

Edit:

natsort() did not work.

sort($array, SORT_NUMERIC) did the job! Thanks.

2

2 Answers 2

0

Try this it will solve your problem:

$ar = [
    "1_some-str",
    "2_some-str",
    "4_some-str",
    "3_some-str",
];

echo "<pre>";
print_r($ar);
echo "</pre>";

natsort($ar);

echo "<pre>";
print_r($ar);
echo "</pre>";
Sign up to request clarification or add additional context in comments.

Comments

0

Use Natsort

    <?php
$myData=array(
"1_some-str",
"5_some-str",   
"3_some-str",
"4_some-str",
"2_some-str",
);

echo "<pre>";
natsort($myData);
print_r($myData);

?>

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.