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
anjanesh
DevNet Resident
Posts: 1679 Joined: Sat Dec 06, 2003 9:52 pm
Location: Mumbai, India
Post
by anjanesh » Wed Aug 10, 2005 1:32 pm
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 » Wed Aug 10, 2005 1:34 pm
Code: Select all
$arr['k0'] = $arr['k1'];
unset($arr['k1'];
anjanesh
DevNet Resident
Posts: 1679 Joined: Sat Dec 06, 2003 9:52 pm
Location: Mumbai, India
Post
by anjanesh » Wed Aug 10, 2005 1:35 pm
Is there any way to just change the key 'name' instead of creating a new one and deleting the old one ?
shiznatix
DevNet Master
Posts: 2745 Joined: Tue Dec 28, 2004 5:57 pm
Location: Tallinn, Estonia
Contact:
Post
by shiznatix » Wed Aug 10, 2005 2:52 pm
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
feyd
Neighborhood Spidermoddy
Posts: 31559 Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA
Post
by feyd » Wed Aug 10, 2005 4:06 pm
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..
harrisonad
Forum Contributor
Posts: 288 Joined: Fri Oct 15, 2004 4:58 am
Location: Philippines
Contact:
Post
by harrisonad » Wed Aug 10, 2005 7:39 pm
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);
feyd
Neighborhood Spidermoddy
Posts: 31559 Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA
Post
by feyd » Wed Aug 10, 2005 7:43 pm
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..