Jim from Oakland Posted July 6, 2006 Share Posted July 6, 2006 In the array (shown below) I need to change the 'name' of one of the (first level) keys.In the example, I'd like to change the key 'Boat' to'Ship' without changing the order of the array entries.['Car']['ID']='445';['Car']['Color']='blue';['Car']['Note']='needs work';['Boat']['ID']='491';['Boat']['Color']='green';['Boat']['Note']='for sale';['Plane']['ID']='420';['Plane']['Color']='azure';['Plane']['Note']='ready';Thanks a billion! Quote Link to comment https://forums.phpfreaks.com/topic/13804-change-key-name-in-associative-array/ Share on other sites More sharing options...
toplay Posted July 6, 2006 Share Posted July 6, 2006 For all intensive purposes, an associative array doesn't have an order. That's why it's referenced by the "key" of the array.You can do the following:[code]<?php$ary['Car']['ID'] = '445';$ary['Car']['Color'] = 'blue';$ary['Car']['Note'] = 'needs work';$ary['Boat']['ID'] = '491';$ary['Boat']['Color'] = 'green';$ary['Boat']['Note'] = 'for sale';$ary['Plane']['ID'] = '420';$ary['Plane']['Color'] = 'azure';$ary['Plane']['Note'] = 'ready';$ary['Ship']['ID'] = $ary['Boat']['ID'];$ary['Ship']['Color'] = $ary['Boat']['Color'];$ary['Ship']['Note'] = $ary['Boat']['Note'];unset($ary['Boat']['ID']);unset($ary['Boat']['Color']);unset($ary['Boat']['Note']);unset($ary['Boat']);echo '<pre>', print_r($ary, TRUE), '</pre>';?>[/code]However, the array will look like this:[quote]Array( [Car] => Array ( [ID] => 445 [Color] => blue [Note] => needs work ) [Plane] => Array ( [ID] => 420 [Color] => azure [Note] => ready ) [Ship] => Array ( [ID] => 491 [Color] => green [Note] => for sale ))[/quote]Which IMO is not wrong, since one can still access it using the 'Ship' key.You might want to rethink what you're trying to do or how you're accessing the associative array. Quote Link to comment https://forums.phpfreaks.com/topic/13804-change-key-name-in-associative-array/#findComment-53652 Share on other sites More sharing options...
.josh Posted July 6, 2006 Share Posted July 6, 2006 just out of curiosity..why do you wanna do this? at face value, all i can suggest (other than toplay's suggestion) is..why not just change it in the code to ship, if you want to use ship instead of boat? Quote Link to comment https://forums.phpfreaks.com/topic/13804-change-key-name-in-associative-array/#findComment-53696 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.