0

I am sorting $myarray with natsort($myarray). The array is sorted and the index numbers are maintained as you can see below.

Before sort

Array ( [0] => 2 C [1] => 3 A [2] => 1 B ) 

After sort

Array ( [2] => 1 B [0] => 2 C [1] => 3 A )

Is it possible to sort without maintaining the index numbers? I expected an array like this after I sort:

Expected result

Array ( [0] => 1 B [1] => 2 C [2] => 3 A )
Black
  • 18,150
  • 39
  • 158
  • 271

6 Answers6

3

Try this

<?php
$your_array = array('2 C', '3 A', '1 B'); 
natsort($your_array);
$your_array = array_values($your_array);
print_r($your_array);
?>
Ankur Tiwari
  • 2,762
  • 2
  • 23
  • 40
1

You can put the array into new variables after fetching the values only like so..$sorted_new_array = array_values($your_sorted_array);

Pardeep Poria
  • 1,049
  • 1
  • 7
  • 12
1

You can use array_values() to reset keys.

OR

sort()

Code using both the functions and creating same output:

<?php
$arr = array ('2 C', '3 A', '1 B');
$sorted = array_values($arr);
echo '<pre>';print_r($sorted);echo '</pre>';

sort($arr);
echo '<pre>';print_r($arr);echo '</pre>';
?>

Output:

Array
(
    [0] => 2 C
    [1] => 3 A
    [2] => 1 B
)
Array
(
    [0] => 1 B
    [1] => 2 C
    [2] => 3 A
)
Pupil
  • 23,834
  • 6
  • 44
  • 66
1

Simply use nasort and array_values function.

The natsort() function sorts an array by using a "natural order" algorithm. The values keep their original keys.

Because the nasort keeps the key, you need to use the array_values, its makes a new array with relative index.

Process

$arr = array('0' => '2 C', '1' => '3 A', '2' => '1 B'); 
natsort($arr);
$arr = array_values($arr);
print_r($arr);

Rresult

Array
(
    [0] => 1 B
    [1] => 2 C
    [2] => 3 A
)
Murad Hasan
  • 9,565
  • 2
  • 21
  • 42
1

You can do a one-liner using normal sort with the natural sort option:

sort($array,SORT_NATURAL);

Example:

$fruits = array("lemon3", "lemon2", "orange2","orange10", "banana4", "apple9");
sort($fruits,SORT_NATURAL);
print_r($fruits);

Array ( [0] => apple9 [1] => banana4 [2] => lemon2 [3] => lemon3 [4] => orange2 [5] => orange10 )

apokryfos
  • 38,771
  • 9
  • 70
  • 114
0
    <?php
$arr = array ('2C', '3A', '1B');
//predefined function
uasort($arr,'sortArray');

function sortArray($indexOne, $indexTwo)
{
    if($indexOne < $indexTwo)

        return -1; 

    if($indexOne > $indexTwo)

        return 1;

    if($indexOne == $indexTwo)

        return 0;
}

$getResult = array_values($arr);
print_r($getResult);
?>
Vinod Kirte
  • 189
  • 1
  • 6