1

I have an array of range type values 257-1024, 1-256, 1025-2056. All these values are dynamically generated and positioned randomed. Before making an output I have to sort them in a numeric ASC order. Using sort or natsort function is giving the output as 1-256,1025-2056, 257-1024 as php recognise it as string. Is there a built in function with which this can be sorted/arranged in numeric range order i.e 1-256, 257-1024, 1025-2056

1

2 Answers 2

2

You can use natsort() function here.

$array = array("257-1024", "1-256", "1025-2056");

$a = natsort($array);

echo "<pre>";

print_r($array);

echo "</pre>";

Output:

Array
(
   [1] => 1-256
   [0] => 257-1024
   [2] => 1025-2056
)

Hope this helps.

Sign up to request clarification or add additional context in comments.

Comments

0

You can do like below using usort().

$array = ['257-1024', '1025-2056', '1-256'];
usort($array, function($a, $b){
    return ((int)explode('-', $a)[1] < (int)explode('-', $b)[0]) ? -1 : 1;
});
print_r($array);

Output is below.

Array
(
    [0] => 1-256
    [1] => 257-1024
    [2] => 1025-2056
)

Comments

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.