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!
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.
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.
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.
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.
This will renumber the keys while preserving the order of elements.
$new_array = array_values($old_array);
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')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With