22

I have an array that is built using the explode() function, but seeing how i'm using it with random/dynamic data, i see that the indexes keep changing:

Array
(
    [2] => Title: Warmly little before cousin sussex entire set Blessing it ladyship.
    [3] => Snippet: Testing
    [4] => Category: Member
    [5] => Tags: little, before, entire
)

I need the array to be ordered starting at 0 always. I am testing with different data and sometimes it starts at 0, and with other tests it begins at different numbers. I researched and came across Array starting at zero but it seems that only applied to that users specific case. The code i'm using to build the array can be seen here: https://stackoverflow.com/a/10484967/1183323

How can i do this?

Community
  • 1
  • 1
Tower
  • 1,287
  • 3
  • 15
  • 25

2 Answers2

58
$your_new_array = array_values($your_old_array);
J. Bruni
  • 20,322
  • 12
  • 75
  • 92
  • This did it, but should there be anything else i should be concerned about implementing this function. – Tower May 09 '12 at 21:19
  • No. According to the manual, "array_values() returns all the values from the input array and indexes numerically the array." – J. Bruni May 09 '12 at 21:20
  • 4
    Note that the manual does not guarantee that order of values will be preserved. – matt Sep 17 '14 at 19:15
12

Use array_merge() to renumber the array:

$your_old_array = array( 2 => 'whatever', 19 => 'huh', 22 => 'yep' );
$your_new_array = array_merge($your_old_array);
print_r($your_new_array);

Prints this:

Array ( 
  [0] => whatever 
  [1] => huh 
  [2] => yep )
Keith Palmer Jr.
  • 27,666
  • 16
  • 68
  • 105
  • This also works, the result i achieved is similar to that of `array_values`, thanks! – Tower May 09 '12 at 21:23
  • 2
    This is similar to array_values but better if you have also string keys in the array along with numeric keys. array_merge() keeps the string keys as it is and rearrange only numeric keys. – Anup_Tripathi Apr 12 '16 at 12:45
  • I would argue that `array_merge` is the better answer. If there are any non-numerical array indices in the array, `array_values` will remove them and re-number them.Only `array_merge` will preserve non-numerical indices whilst re-indexing only numerical indices. – James Ludlow Sep 16 '16 at 10:29