7

I have an array that looks like this:

[867324]  
    [id] => 867324  
    [name] => Example1  

[345786]    
    [id] => 345786
    [name] => Example2

[268531]  
    [id] => 268531
    [name] => Example3 

So as you can see, the first elements aren't in any specific order. For the purpose of the example, you can just consider them random numbers. The end result I would like to end up with is:

[0]  
    [id] => 867324  
    [name] => Example1  

[1]    
    [id] => 345786
    [name] => Example2

[2]  
    [id] => 268531
    [name] => Example3  

I've tried exploding, but clearly I must be doing something wrong. Any help is appreciated!

Kevin Murphy
  • 378
  • 8
  • 24

3 Answers3

32

This will renumber the keys while preserving the order of elements.

$new_array = array_values($old_array);
kijin
  • 8,702
  • 2
  • 26
  • 32
  • Ah, that's what it is. Now just curious - how fast is this type of process for a fairly large array? – Kevin Murphy May 05 '12 at 17:43
  • It's rather slow. I just whipped up a script to renumber a 1,000 element array repeatedly, and my 2.8GHz machine can barely manage 8,000 iterations per second. You definitely don't want to do this on every page load if you have more than a few dozen elements. – kijin May 05 '12 at 17:54
  • Well I'm not replacing the keys on every single element. Just about 10 xD – Kevin Murphy May 05 '12 at 17:59
8

You can reset the array keys using array_values():

$array = array_values($array);

Using this method an array such as:

Array('123'=>'123',
      '456'=>'456',
      '789'=>'789')

Will be renumbered like:

Array('0'=>'123',
      '1'=>'456',
      '2'=>'789')
Jeremy Harris
  • 24,318
  • 13
  • 79
  • 133
1

If the order of elements doesn't matter, I believe PHPs sort method will not maintain indexes. http://www.php.net/manual/en/function.sort.php

sort($array);

Note: This function assigns new keys to the elements in array. It will remove any existing keys that may have been assigned, rather than just reordering the keys.

Update: This does work, though the array_values method mentioned makes much more sense.

Lix
  • 47,311
  • 12
  • 103
  • 131
Dan LaManna
  • 3,431
  • 4
  • 23
  • 35