View Full Version : Can I reset array keys?

04-06-2003, 04:43 PM
Best explained as an example:

$array[8] = 'Bob';
$array[17] = 'Geoff';
$array[2] = 'Alice';

Can I get the above array to become this?

$array[0] = 'Alice';
$array[1] = 'Bob';
$array[2] = 'Geoff';

The names are examples... I do not want any change in the order of the array. I simply want the keys to be like this so I can access the data more easily.

If there is not a simple solution that i have overlooked then I will post here later with more information of what I am actually trying to achieve.

Thanks in advance :)

04-06-2003, 05:36 PM
there must be a simpler way but I am yakked if I can think of it right now ?

$array[8] = 'Bob';
$array[17] = 'Geoff';
$array[2] = 'Alice';

//if you want


04-06-2003, 06:49 PM
strangely the results of what you wrote do this:

[0] => Bob
[1] => Geoff
[2] => Alice

which is actually in the wrong order.

$array[8] = 'Bob';
$array[17] = 'Geoff';
$array[2] = 'Alice';

^^^ with that as the original array, should it not come out as this?:

[0] => Alice
[1] => Bob
[2] => Geoff

the code may still work for me as the array *should* have already been loaded in the correct order. thanks again for your help :)

08-25-2008, 01:00 PM
I know that post is too old but since it is in google's result for the keyword 'php reset array keys' I have decided to add the solution to help others ;)

The first idea which came to my mind was this:

$threads = array('10'=>'one', '2'=>'two', '15'=>'three');
$keys = range(0, count($threads)-1);
$values = array_values($threads);
$threads = array_combine($keys, $values);

but later I have discovered that there is even more simple way :)

$threads = array('10'=>'one', '2'=>'two', '15'=>'three');
$threads = array_values($threads);

Good luck with your script

02-02-2009, 08:28 AM
Thanks PHP6, I was looking for that. :thumbsup:

02-02-2009, 06:00 PM
array_merge (http://php.ca/manual/en/function.array-merge.php)
Given a single array, it will reindex the values for you as long as they are integer based.

02-03-2009, 06:55 AM
If your array is out of order, like the OP was talking about, run ksort() (http://php.net/ksort) on it before using array_values() (http://php.net/array_values) or array_merge() (http://php.net/array_merge).

EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum