Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Modify array key

Status
Not open for further replies.

rob51383

Programmer
Jun 23, 2004
134
US
How can you modify the key of an array?

$array = array(one => 1, two => 2);

$array[one] = "changeTheKeyNotTheValue";

array
{
[changeTheKeyNotTheValue] => 1
[two] => 2
}

Thanks.
 
swap and unset

Code:
$array = array('one' => 1, 'two' => 2);
$array['new'] = $array['one'];
unset($array['one']);

You can go ahead and just functionalize that as

Code:
function newKey(&$arr, $oldkey,$newkey)
{
  $arr[$newkey]=$arr[$oldkey];
  unset($arr['oldkey']);
 //Add your own error handling based on need
}
 
oh just for the record, that will actually give you

array
{
[two] => 2
[change TheKeyNotThevalue] => 1
}

so careful about any assumptions you may be making on array orderings.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top