PHP: Reassign array keys

12,572

Solution 1

You can use sort [docs] with SORT_NUMERIC, instead of natsort:

sort($times, SORT_NUMERIC);

Unlike natsort, it re-indexes the array.


There is no built in way to re-index the array after/while sorting. You could also use array_values [docs] after sorting with natsort:

$times = array_values($times);

This is copying the array though.

Solution 2

You can do this with array_values.

$times=array_values($times);

Solution 3

usort reassigns array keys after sorting, use it with strnatcmp:

usort( $times, 'strnatcmp' );
Share:
12,572
dukevin
Author by

dukevin

.-"-.__ | .' / ,-| ```'-, || . ` / /@)|_ `-, | / ( ~ \_```""--.,_', : _.' \ /```''''""`^ / | / `| : / \/ | | . / __/ | |. | | __/ / | | | "-._ | _/ _/=_// || : '. `~~`~^| /=/-_/_/`~~`~~~`~~`~^~`. `> ' . \ ~/_/_ /" ` . ` ' . | .' ,'~^~`^| |~^`^~~`~~~^~~~^~`; ' .-' | | | \ ` : ` | :| | : | |: | || ' | |/ | | : |_/ | . '

Updated on June 07, 2022

Comments

  • dukevin
    dukevin almost 2 years

    I have an array of numbers from descending order. When I add to this array, I add to the end and then do natsort($times). $times then looks like this (obtained by print_r):

    Array
    (
        [0] => 0.01
        [1] => 0.02
        [2] => 0.05
        [3] => 0.08
        [7] => 0.10   <-- Just added and natsorted
        [4] => 0.11
        [5] => 0.14
        [6] => 0.21
    )
    

    However, I wish to reassign all the keys so that the just-added 0.10 is array index 4 making it easy to see what place the new time is in. ie "your ranking is $arrayindex+1"

    Besides copying this whole array into a new array to get new keys, is there a better way?

  • Micromega
    Micromega over 12 years
    Why should he? Is this faster?
  • Felix Kling
    Felix Kling over 12 years
    @Jitamaro: What do you mean? I mean he should use sort instead of natsort. This will be faster (well, depends on what array_values is doing under the hood, but it is likely that calling only one method is faster than calling two).
  • dukevin
    dukevin over 12 years
    sort($times, SORT_NUMERIC); worked perfectly for me as an alternative to natsort