Changing the key of an Array

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
User avatar
anjanesh
DevNet Resident
Posts: 1679
Joined: Sat Dec 06, 2003 9:52 pm
Location: Mumbai, India

Changing the key of an Array

Post by anjanesh »

Is there any way to change the key of an array ?

Code: Select all

$arr = array("k1"=>"v1", "k2"=>"v2");
// I now want the array to be array("k0"=>"v1", "k2"=>"v2");
Thanks
timvw
DevNet Master
Posts: 4897
Joined: Mon Jan 19, 2004 11:11 pm
Location: Leuven, Belgium

Post by timvw »

Code: Select all

$arr['k0'] = $arr['k1'];
unset($arr['k1'];
User avatar
anjanesh
DevNet Resident
Posts: 1679
Joined: Sat Dec 06, 2003 9:52 pm
Location: Mumbai, India

Post by anjanesh »

Is there any way to just change the key 'name' instead of creating a new one and deleting the old one ?
User avatar
shiznatix
DevNet Master
Posts: 2745
Joined: Tue Dec 28, 2004 5:57 pm
Location: Tallinn, Estonia
Contact:

Post by shiznatix »

there are different ways of "sorting" the array that will change the key but there is no way that I know of to change the key without unsetting the other key afterwards
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

in the end it always involves setting a new one, and destroying an old one.. whether you do it in the code, or it's hidden behind the scenes..
User avatar
harrisonad
Forum Contributor
Posts: 288
Joined: Fri Oct 15, 2004 4:58 am
Location: Philippines
Contact:

Post by harrisonad »

although it is more tasks, I suggest to use array_combine()

Code: Select all

$arr = array("k1"=>"v1", "k2"=>"v2");
$keys = ("k0","k1");
$result_aray = array_combine($keys,$aray);
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

note: array_combine() was not available until PHP 5.

however, it's not that hard to create your own version if you have PHP 4..
Post Reply