Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace Array Keys with Ascending Numbers

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!

like image 298
Kevin Murphy Avatar asked May 05 '12 17:05

Kevin Murphy


People also ask

How do you change array keys?

There is an alternative way to change the key of an array element when working with a full array - without changing the order of the array. It's simply to copy the array into a new 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.

How do you remove an array from a key?

Using unset() Function: The unset() function is used to remove element from the array. The unset function is used to destroy any other variable and same way use to delete any element of an array. This unset command takes the array key as input and removed that element from the array.

How do I get all array keys?

The array_keys() function is used to get all the keys or a subset of the keys of an array. Note: If the optional search_key_value is specified, then only the keys for that value are returned. Otherwise, all the keys from the array are returned.


2 Answers

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

$new_array = array_values($old_array);
like image 135
kijin Avatar answered Dec 25 '22 14:12

kijin


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')
like image 33
Jeremy Harris Avatar answered Dec 25 '22 15:12

Jeremy Harris