Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP: Reassign array keys

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?

like image 562
dukevin Avatar asked Aug 07 '11 09:08

dukevin


People also ask

How to replace array key value in PHP?

The array_replace() function replaces the values of the first array with the values from following arrays. Tip: You can assign one array to the function, or as many as you like. If a key from array1 exists in array2, values from array1 will be replaced by the values from array2.

How do you assign a key to an array?

To add a key/value pair to all objects in an array:Use the Array. forEach() method to iterate over the array. On each iteration, use dot notation to add a key/value pair to the current object. The key/value pair will get added to all objects in the array.

How do you change the key of an associative array?

Just make a note of the old value, use unset to remove it from the array then add it with the new key and the old value pair. Save this answer.


2 Answers

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.

like image 126
Felix Kling Avatar answered Sep 30 '22 19:09

Felix Kling


You can do this with array_values.

$times=array_values($times);
like image 34
Micromega Avatar answered Sep 30 '22 17:09

Micromega