Reputation: 289
I have a array with:
$strings = ['n/a', '2 years', '3 years', '4 years', '5 years', '1 year'];
How I can order years? I need get result:
$strings = ['n/a', '1 year', '2 years', '3 years', '4 years', '5 years'];
sort
function is not work in this cause. Thanks for helping :)
Upvotes: 2
Views: 73
Reputation: 72289
<?php
$strings = ['n/a', '2 years', '3 years', '4 years', '5 years', '1 year'];
// remove first value from array and save it in a variable
$first_val = array_shift($strings);
//sort array based on string comparison
usort($strings, "strcmp");
//add removed value again at first position of the array
array_unshift($strings,$first_val);
//print array to see everything fine or not?
print_r($strings);
Output:-https://3v4l.org/4TcBi
Note:- In case n/a
is not the first value then do like below:
Upvotes: -1
Reputation: 3080
This should work:
$strings = ['n/a', '1 year', '2 years', '3 years', '4 years', '5 years'];
$numbers = array();
$albhabets = array();
foreach($strings as $v)
{
if(is_numeric($v[0]))
{
array_push($numbers,$v);
}else
{
array_push($albhabets,$v);
}
}
sort($numbers);
sort($albhabets);
print_r(array_merge($albhabets,$numbers));
Upvotes: 0
Reputation: 131
Would it can help you
$strings = ['n/a', '2 years', '3 years', '4 years', '5 years', '1 year'];
usort($strings, function($a, $b) {
if ($a == 'n/a') {
return 0;
}
return ($a < $b) ? -1 : 1;
});
Upvotes: 1
Reputation: 751
May be it will help you:
sort($strings, SORT_NATURAL | SORT_FLAG_CASE);
Upvotes: 1