{"id":2526,"date":"2017-11-24T12:56:37","date_gmt":"2017-11-24T07:26:37","guid":{"rendered":"http:\/\/fellowtuts.com\/?p=2526"},"modified":"2018-12-09T00:39:42","modified_gmt":"2018-12-08T19:09:42","slug":"change-array-key-without-changing-order","status":"publish","type":"post","link":"https:\/\/fellowtuts.com\/php\/change-array-key-without-changing-order\/","title":{"rendered":"3 Ways to Change Array Key without Changing the Order in PHP"},"content":{"rendered":"<p>You can change array key too easily but doing it without\u00a0changing the order in PHP is quite tricky. Simply assigning the value to a new key and deleting old one doesn&#8217;t change the position of the new key at the\u00a0place of old in the array.<\/p>\n<p>So in this article, I have explained 3 ways to let you change array key while maintaining the key order and last one of them can be used with a multidimensional array as well. But before that, if you just need to rename a key without preserving the order, the two lines code does the job:<\/p>\n<pre class=\"lang:default decode:true\" title=\"Rename array key without preserving order\">$arr[$newkey] = $arr[$oldkey];\r\nunset($arr[$oldkey]);<\/pre>\n<ul>\n<li><a href=\"https:\/\/fellowtuts.com\/interview-questions\/php-interview-questions\/\" target=\"_blank\" rel=\"noopener\">PHP Interview Questions<\/a>.<\/li>\n<li>Convert a\u00a0<a href=\"https:\/\/fellowtuts.com\/php\/multidimensional-array-object-conversion\/\" target=\"_blank\" rel=\"noopener\">multidimensional array to object<\/a>.<\/li>\n<\/ul>\n<h3>1. Change Array Key using\u00a0JSON encode\/decode<\/h3>\n<pre class=\"lang:default decode:true\" title=\"Change Array Key using JSON encode\/decode\">function json_change_key($arr, $oldkey, $newkey) {\r\n\t$json = str_replace('\"'.$oldkey.'\":', '\"'.$newkey.'\":', json_encode($arr));\r\n\treturn json_decode($json);\t\r\n}<\/pre>\n<p>It&#8217;s short but be careful while using it. Use only to change key when you&#8217;re sure that your array doesn&#8217;t contain value exactly same as old key plus a colon. Otherwise, the <a href=\"http:\/\/fellowtuts.com\/php\/find-object-by-value-in-array-of-objects\/\" target=\"_blank\" rel=\"noopener\">value\u00a0or object value<\/a> will also get replaced.<\/p>\n<p>&nbsp;<\/p>\n<h3>2. Replace key &amp; Maintain Order using Array Functions in PHP<\/h3>\n<pre class=\"lang:default decode:true\">function replace_key($arr, $oldkey, $newkey) {\r\n\tif(array_key_exists( $oldkey, $arr)) {\r\n\t\t$keys = array_keys($arr);\r\n    \t$keys[array_search($oldkey, $keys)] = $newkey;\r\n\t    return array_combine($keys, $arr);\t\r\n\t}\r\n    return $arr;    \r\n}<\/pre>\n<p>The function<code>replace_key()<\/code> first checks if old key exists in the\u00a0array? If yes then creates an Indexed Array of keys from source array and change old key with new using PHP\u00a0<em>array_search()<\/em> <a href=\"http:\/\/php.net\/manual\/en\/ref.array.php\" target=\"_blank\" rel=\"noopener nofollow\">function<\/a>.<\/p>\n<p>Finally, <a href=\"http:\/\/fellowtuts.com\/php\/merge-two-arrays-php\/\" target=\"_blank\" rel=\"noopener\"><em>array_combine()<\/em><\/a> function returns a\u00a0new\u00a0array with key changed, taking keys from the created indexed array and values from source array.\u00a0The non-existence\u00a0of old key just simply returns the array without any change.<\/p>\n<p>&nbsp;<\/p>\n<h3>3. Change Array Key without Changing the Order (Multidimensional Array Capable)<\/h3>\n<pre class=\"lang:default mark:21 decode:true\" title=\"Change array key - multidimensional array\">\/\/$arr =&gt; original array\r\n\/\/$set =&gt; array containing old keys as keys and new keys as values\r\nfunction recursive_change_key($arr, $set) {\r\n        if (is_array($arr) &amp;&amp; is_array($set)) {\r\n    \t\t$newArr = array();\r\n    \t\tforeach ($arr as $k =&gt; $v) {\r\n    \t\t    $key = array_key_exists( $k, $set) ? $set[$k] : $k;\r\n    \t\t    $newArr[$key] = is_array($v) ? recursive_change_key($v, $set) : $v;\r\n    \t\t}\r\n    \t\treturn $newArr;\r\n    \t}\r\n    \treturn $arr;    \r\n    }\r\n\r\n    $ppl = array(\r\n        'jack' =&gt; array('address_2' =&gt; 'London', 'country' =&gt; 'UK'),\r\n        'jill' =&gt; array('address_2' =&gt; 'Washington', 'country' =&gt; 'US')\r\n    );\r\n   \r\n   $people = recursive_change_key($ppl, array('jill' =&gt; 'john', 'address_2' =&gt; 'city'));\r\n   \r\n   print_r($people);\r\n\r\n\r\n\/*\r\n====================================\r\nOutput:\r\nArray\r\n(\r\n    [jack] =&gt; Array\r\n        (\r\n            [city] =&gt; London\r\n            [country] =&gt; UK\r\n        )\r\n\r\n    [john] =&gt; Array\r\n        (\r\n            [city] =&gt; Washington\r\n            [country] =&gt; US\r\n        )\r\n\r\n)\r\n*\/<\/pre>\n<p>This solution is quite elegant\u00a0and <strong>can work with multidimensional array too<\/strong> with help of classic PHP loop and recursive\u00a0function call. Let&#8217;s see how are we doing this change.<\/p>\n<p>Here we need to pass two arrays in the function call (Line #20). The first parameter is the array which needs to change keys and another is an array containing indexes as old keys and values as new keys. Upon execution, the function will change all the keys in the first array which are present in the second array too and their respective values will be new keys.<\/p>\n<p>The recursive calling within function ensures changing keys up to\u00a0the deepest branch of the array. The function<code>recursive_change_key()<\/code> here is provided along with the example to understand better.<\/p>\n<p>Don&#8217;t forget to read our extensive list of 38 <a href=\"http:\/\/fellowtuts.com\/php\/\" target=\"_blank\" rel=\"noopener\">PHP related tutorials<\/a> yet.<\/p>\n<p>So here you got 3 ways to change array key without changing the order of array in PHP. And the last one works with a multidimensional array as well. All you need is just to provide correct set of &#8220;old key, new key&#8221; pairs for changing purpose.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>You can change array key too easily but doing it without\u00a0changing the order in PHP is quite tricky. Simply assigning the value to a new key and deleting old one doesn&#8217;t change the position of the new key at the\u00a0place of old in the array.<\/p>\n<p class=\"text-right mb-0\"><a class=\"btn btn-outline-primary\" href=\"https:\/\/fellowtuts.com\/php\/change-array-key-without-changing-order\/\">Read More<\/a><\/p>","protected":false},"author":3,"featured_media":2553,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"_jetpack_memberships_contains_paid_content":false,"footnotes":"","jetpack_publicize_message":"","jetpack_publicize_feature_enabled":true,"jetpack_social_post_already_shared":true,"jetpack_social_options":{"image_generator_settings":{"template":"highway","default_image_id":0,"font":"","enabled":false},"version":2}},"categories":[18],"tags":[29,46,53],"class_list":["post-2526","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-php","tag-array","tag-function","tag-functionality"],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v26.8 - https:\/\/yoast.com\/product\/yoast-seo-wordpress\/ -->\n<title>3 Ways to Change Array Key without Changing the Order in PHP<\/title>\n<meta name=\"description\" content=\"You can change array key easily but doing it without\u00a0changing the order in a PHP multidimensional array is tricky. To change array key &amp; maintaining order\" \/>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/fellowtuts.com\/php\/change-array-key-without-changing-order\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"3 Ways to Change Array Key without Changing the Order in PHP\" \/>\n<meta property=\"og:description\" content=\"You can change array key easily but doing it without\u00a0changing the order in a PHP multidimensional array is tricky. To change array key &amp; maintaining order\" \/>\n<meta property=\"og:url\" content=\"https:\/\/fellowtuts.com\/php\/change-array-key-without-changing-order\/\" \/>\n<meta property=\"og:site_name\" content=\"Fellow Tuts\" \/>\n<meta property=\"article:publisher\" content=\"https:\/\/www.facebook.com\/FellowTuts\/\" \/>\n<meta property=\"article:published_time\" content=\"2017-11-24T07:26:37+00:00\" \/>\n<meta property=\"article:modified_time\" content=\"2018-12-08T19:09:42+00:00\" \/>\n<meta property=\"og:image\" content=\"https:\/\/fellowtuts.com\/wp-content\/uploads\/2017\/11\/change-array-key-without-changing-order.jpg\" \/>\n\t<meta property=\"og:image:width\" content=\"600\" \/>\n\t<meta property=\"og:image:height\" content=\"600\" \/>\n\t<meta property=\"og:image:type\" content=\"image\/jpeg\" \/>\n<meta name=\"author\" content=\"Amit Sonkhiya\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:creator\" content=\"@SonkhiyaAmit\" \/>\n<meta name=\"twitter:site\" content=\"@fellowtuts\" \/>\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"Amit Sonkhiya\" \/>\n\t<meta name=\"twitter:label2\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"3 minutes\" \/>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"3 Ways to Change Array Key without Changing the Order in PHP","description":"You can change array key easily but doing it without\u00a0changing the order in a PHP multidimensional array is tricky. To change array key & maintaining order","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/fellowtuts.com\/php\/change-array-key-without-changing-order\/","og_locale":"en_US","og_type":"article","og_title":"3 Ways to Change Array Key without Changing the Order in PHP","og_description":"You can change array key easily but doing it without\u00a0changing the order in a PHP multidimensional array is tricky. To change array key & maintaining order","og_url":"https:\/\/fellowtuts.com\/php\/change-array-key-without-changing-order\/","og_site_name":"Fellow Tuts","article_publisher":"https:\/\/www.facebook.com\/FellowTuts\/","article_published_time":"2017-11-24T07:26:37+00:00","article_modified_time":"2018-12-08T19:09:42+00:00","og_image":[{"width":600,"height":600,"url":"https:\/\/fellowtuts.com\/wp-content\/uploads\/2017\/11\/change-array-key-without-changing-order.jpg","type":"image\/jpeg"}],"author":"Amit Sonkhiya","twitter_card":"summary_large_image","twitter_creator":"@SonkhiyaAmit","twitter_site":"@fellowtuts","twitter_misc":{"Written by":"Amit Sonkhiya","Est. reading time":"3 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"Article","@id":"https:\/\/fellowtuts.com\/php\/change-array-key-without-changing-order\/#article","isPartOf":{"@id":"https:\/\/fellowtuts.com\/php\/change-array-key-without-changing-order\/"},"author":{"name":"Amit Sonkhiya","@id":"https:\/\/fellowtuts.com\/#\/schema\/person\/b9570d93920c6122e8d31c5827a3c494"},"headline":"3 Ways to Change Array Key without Changing the Order in PHP","datePublished":"2017-11-24T07:26:37+00:00","dateModified":"2018-12-08T19:09:42+00:00","mainEntityOfPage":{"@id":"https:\/\/fellowtuts.com\/php\/change-array-key-without-changing-order\/"},"wordCount":450,"commentCount":14,"image":{"@id":"https:\/\/fellowtuts.com\/php\/change-array-key-without-changing-order\/#primaryimage"},"thumbnailUrl":"https:\/\/fellowtuts.com\/wp-content\/uploads\/2017\/11\/change-array-key-without-changing-order.jpg","keywords":["Array","Function","Functionality"],"articleSection":["PHP"],"inLanguage":"en-US","potentialAction":[{"@type":"CommentAction","name":"Comment","target":["https:\/\/fellowtuts.com\/php\/change-array-key-without-changing-order\/#respond"]}]},{"@type":"WebPage","@id":"https:\/\/fellowtuts.com\/php\/change-array-key-without-changing-order\/","url":"https:\/\/fellowtuts.com\/php\/change-array-key-without-changing-order\/","name":"3 Ways to Change Array Key without Changing the Order in PHP","isPartOf":{"@id":"https:\/\/fellowtuts.com\/#website"},"primaryImageOfPage":{"@id":"https:\/\/fellowtuts.com\/php\/change-array-key-without-changing-order\/#primaryimage"},"image":{"@id":"https:\/\/fellowtuts.com\/php\/change-array-key-without-changing-order\/#primaryimage"},"thumbnailUrl":"https:\/\/fellowtuts.com\/wp-content\/uploads\/2017\/11\/change-array-key-without-changing-order.jpg","datePublished":"2017-11-24T07:26:37+00:00","dateModified":"2018-12-08T19:09:42+00:00","author":{"@id":"https:\/\/fellowtuts.com\/#\/schema\/person\/b9570d93920c6122e8d31c5827a3c494"},"description":"You can change array key easily but doing it without\u00a0changing the order in a PHP multidimensional array is tricky. To change array key & maintaining order","breadcrumb":{"@id":"https:\/\/fellowtuts.com\/php\/change-array-key-without-changing-order\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/fellowtuts.com\/php\/change-array-key-without-changing-order\/"]}]},{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/fellowtuts.com\/php\/change-array-key-without-changing-order\/#primaryimage","url":"https:\/\/fellowtuts.com\/wp-content\/uploads\/2017\/11\/change-array-key-without-changing-order.jpg","contentUrl":"https:\/\/fellowtuts.com\/wp-content\/uploads\/2017\/11\/change-array-key-without-changing-order.jpg","width":600,"height":600,"caption":"Change Array Key without Changing the Order in PHP"},{"@type":"BreadcrumbList","@id":"https:\/\/fellowtuts.com\/php\/change-array-key-without-changing-order\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https:\/\/fellowtuts.com\/"},{"@type":"ListItem","position":2,"name":"PHP","item":"https:\/\/fellowtuts.com\/php\/"},{"@type":"ListItem","position":3,"name":"3 Ways to Change Array Key without Changing the Order in PHP"}]},{"@type":"WebSite","@id":"https:\/\/fellowtuts.com\/#website","url":"https:\/\/fellowtuts.com\/","name":"Fellow Tuts","description":"Application Development &amp; Informative Tutorials by Fellow Tuts","potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/fellowtuts.com\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"en-US"},{"@type":"Person","@id":"https:\/\/fellowtuts.com\/#\/schema\/person\/b9570d93920c6122e8d31c5827a3c494","name":"Amit Sonkhiya","image":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/fellowtuts.com\/#\/schema\/person\/image\/","url":"https:\/\/secure.gravatar.com\/avatar\/d92d9ad9c56711a79f1a10988743adb3?s=96&d=mm&r=g","contentUrl":"https:\/\/secure.gravatar.com\/avatar\/d92d9ad9c56711a79f1a10988743adb3?s=96&d=mm&r=g","caption":"Amit Sonkhiya"},"description":"Entrepreneur, multiple programming skills and technology lover.","sameAs":["https:\/\/x.com\/SonkhiyaAmit"],"url":"https:\/\/fellowtuts.com\/author\/amit\/"}]}},"jetpack_publicize_connections":[],"jetpack_featured_media_url":"https:\/\/fellowtuts.com\/wp-content\/uploads\/2017\/11\/change-array-key-without-changing-order.jpg","jetpack_shortlink":"https:\/\/wp.me\/p4hwPY-EK","jetpack_sharing_enabled":true,"_links":{"self":[{"href":"https:\/\/fellowtuts.com\/wp-json\/wp\/v2\/posts\/2526","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/fellowtuts.com\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/fellowtuts.com\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/fellowtuts.com\/wp-json\/wp\/v2\/users\/3"}],"replies":[{"embeddable":true,"href":"https:\/\/fellowtuts.com\/wp-json\/wp\/v2\/comments?post=2526"}],"version-history":[{"count":2,"href":"https:\/\/fellowtuts.com\/wp-json\/wp\/v2\/posts\/2526\/revisions"}],"predecessor-version":[{"id":3707,"href":"https:\/\/fellowtuts.com\/wp-json\/wp\/v2\/posts\/2526\/revisions\/3707"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/fellowtuts.com\/wp-json\/wp\/v2\/media\/2553"}],"wp:attachment":[{"href":"https:\/\/fellowtuts.com\/wp-json\/wp\/v2\/media?parent=2526"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/fellowtuts.com\/wp-json\/wp\/v2\/categories?post=2526"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/fellowtuts.com\/wp-json\/wp\/v2\/tags?post=2526"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}