Page 1 of 1

Changing the key of an Array

Posted: Wed Aug 10, 2005 1:32 pm
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

Posted: Wed Aug 10, 2005 1:34 pm
by timvw

Code: Select all

$arr['k0'] = $arr['k1'];
unset($arr['k1'];

Posted: Wed Aug 10, 2005 1:35 pm
by anjanesh
Is there any way to just change the key 'name' instead of creating a new one and deleting the old one ?

Posted: Wed Aug 10, 2005 2:52 pm
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

Posted: Wed Aug 10, 2005 4:06 pm
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..

Posted: Wed Aug 10, 2005 7:39 pm
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);

Posted: Wed Aug 10, 2005 7:43 pm
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..