php array change array key
3 Ways to Change Array Key without Changing the Order in PHP
DISCLOSURE: This article may contain affiliate links and any sales made through such links will reward us a small commission, at no extra cost for you. Read more about Affiliate Disclosure here.
You can change array key too easily but doing it without changing the order in PHP is quite tricky. Simply assigning the value to a new key and deleting old one doesn’t change the position of the new key at the place of old in the array.
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:
1. Change Array Key using JSON encode/decode
It’s short but be careful while using it. Use only to change key when you’re sure that your array doesn’t contain value exactly same as old key plus a colon. Otherwise, the value or object value will also get replaced.
2. Replace key & Maintain Order using Array Functions in PHP
The function replace_key() first checks if old key exists in the array? If yes then creates an Indexed Array of keys from source array and change old key with new using PHP array_search() function.
Finally, array_combine() function returns a new array with key changed, taking keys from the created indexed array and values from source array. The non-existence of old key just simply returns the array without any change.
3. Change Array Key without Changing the Order (Multidimensional Array Capable)
This solution is quite elegant and can work with multidimensional array too with help of classic PHP loop and recursive function call. Let’s see how are we doing this change.
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.
The recursive calling within function ensures changing keys up to the deepest branch of the array. The function recursive_change_key() here is provided along with the example to understand better.
Don’t forget to read our extensive list of 38 PHP related tutorials yet.
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 “old key, new key” pairs for changing purpose.
You Might Interested In
13 COMMENTS
Edit: ( in the unit test \TGHelpers_Array::renameKeyKeepingOrder is where i put the function replace_key() )
It’s nice that you improved the function to consist of numeric/floating keys.
A little bit more complicated, but can do associative arrays with out having to create a new array: http://php.net/manual/en/function.array-walk.php#122991
That’s good. Yet that piece of code requires more processing time as well as passing many parameters which isn’t less than memory occupied by the temporary array created here.
That’s good. Yet that piece of code requires more processing time as well as passing many parameters which isn’t less than memory occupied by the temporary array created here.
I didn’t say it was a better way, just another way. =P
Haha lol. I admit you’re smarter than me.
I wouldn’t say I’m “smart”. Just more determine to do crazy things.
That’s nice habit until things don’t get complicated :-D. Have a good time ahead!
Serialization, regular expression and JSON string always have performance issue. Rest all are around near except the benchArrayKeys.
I think there is a typo
Line 6 : it rather be
because it’s recursive 😀
Leave a Reply Cancel reply
GET IN TOUCH
WE’RE AVAILABLE
AS Tech Solutions is an Android Apps and Web Design & Development company, offering the following services:
FACEBOOK FANS
Hey buddy 🙋♂️ SUP? I’m Amit, a passionate tech blogger and Android & web application developer. Check our services and enjoy these hand-picked articles as well:
array_replace
(PHP 5 >= 5.3.0, PHP 7, PHP 8)
array_replace — Заменяет элементы массива элементами других переданных массивов
Описание
array_replace() не рекурсивная: значения первого массива будут заменены вне зависимости от типа значений второго массива, даже если это будут вложенные массивы.
Список параметров
Массив, элементы которого требуется заменить.
Массивы, из которых будут браться элементы для замены. Значения следующего массива затирают значения предыдущего.
Возвращаемые значения
Возвращает массив ( array ) или null в случае возникновения ошибки.
Примеры
Пример #1 Пример использования array_replace()
Результат выполнения данного примера:
Смотрите также
User Contributed Notes 14 notes
// we wanted the output of only selected array_keys from a big array from a csv-table
// with different order of keys, with optional suppressing of empty or unused values
Here is a simple array_replace_keys function:
print_r(array_replace_keys([‘one’=>’apple’, ‘two’=>’orange’], [‘one’=>’ett’, ‘two’=>’tvo’]);
// Output
array(
‘ett’=>’apple’,
‘tvo’=>’orange’
)
Simple function to replace array keys. Note you have to manually select wether existing keys will be overrided.
To get exactly same result like in PHP 5.3, the foreach loop in your code should look like:
array(3) <
«id» => NULL
«login» => string(8) «john.doe»
«credit» => int(100)
>
I would like to add to my previous note about my polecat_array_replace function that if you want to add a single dimensional array to a multi, all you must do is pass the matching internal array key from the multi as the initial argument as such:
$array1 = array( «berries» => array( «strawberry» => array( «color» => «red», «food» => «desserts»), «dewberry» = array( «color» => «dark violet», «food» => «pies»), );
$array2 = array( «food» => «wine»);
This is will replace the value for «food» for «dewberry» with «wine».
The function will also do the reverse and add a multi to a single dimensional array or even a 2 tier array to a 5 tier as long as the heirarchy tree is identical.
I hope this helps atleast one person for all that I’ve gained from this site.
I got hit with a noob mistake. 🙂
When the function was called more than once, it threw a function redeclare error of course. The enviroment I was coding in never called it more than once but I caught it in testing and here is the fully working revision. A simple logical step was all that was needed.
With PHP 5.3 still unstable for Debian Lenny at this time and not knowing if array_replace would work with multi-dimensional arrays, I wrote my own. Since this site has helped me so much, I felt the need to return the favor. 🙂
$array2 = array( «food» => «wine» );
The function will also do the reverse and add a multi to a single dimensional array or even a 2 tier array to a 5 tier as long as the heirarchy tree is identical.
I hope this helps atleast one person for all that I’ve gained from this site.
In some cases you might have a structured array from the database and one
of its nodes goes like this;
# string to transform
$string = «
name: %s, json: %s, title: %s
?>
I hope that this will save someone’s time.
array_fill_keys
(PHP 5 >= 5.2.0, PHP 7, PHP 8)
array_fill_keys — Fill an array with values, specifying keys
Description
Fills an array with the value of the value parameter, using the values of the keys array as keys.
Parameters
Value to use for filling
Return Values
Returns the filled array
Examples
Example #1 array_fill_keys() example
The above example will output:
See Also
User Contributed Notes 8 notes
now string key «1» become an integer value 1, be careful.
Some of the versions do not have this function.
I try to write it myself.
You may refer to my script below
RE: bananasims at hotmail dot com
I also needed a work around to not having a new version of PHP and wanting my own keys. bananasims code doesn’t like having an array as the second parameter.
Here’s a slightly modified version than can handle 2 arrays as inputs:
//we want these values to be keys
$arr1 = (0 => «abc», 1 => «def»);
/we want these values to be values
$arr2 = (0 => 452, 1 => 128);
returns:
abc => 452, def =>128
Scratchy’s version still doesn’t work like the definition describes. Here’s one that can take a mixed variable as the second parameter, defaulting to an empty string if it’s not specified. Don’t know if this is exactly how the function works in later versions but it’s at least a lot closer.
This works for either strings or numerics, so if we have
$arr1 = array(0 => ‘abc’, 1 => ‘def’);
$arr2 = array(0 => 452, 1 => 128);
$arr3 = array(0 => ‘foo’, 1 => ‘bar’);
array_fill_keys($arr1,$arr2)
returns: [abc] => 452, [def] => 128
array_fill_keys($arr1,0)
returns: [abc] => 0, [def] => 0
array_fill_keys($arr2,$arr3)
returns: [452] => foo, [128] => bar
array_fill_keys($arr3,’BLAH’)
returns: [foo] => BLAH, [bar] => BLAH
and array_fill_keys($arr1)
returns: [abc] =>, [def] =>
array_key_exists
(PHP 4 >= 4.0.7, PHP 5, PHP 7, PHP 8)
array_key_exists — Проверяет, присутствует ли в массиве указанный ключ или индекс
Описание
Список параметров
Массив с проверяемыми ключами.
Возвращаемые значения
Возвращает true в случае успешного выполнения или false в случае возникновения ошибки.
array_key_exists() ищет ключи только на первом уровне массива. Внутренние ключи в многомерных массивах найдены не будут.
Примеры
Пример #1 Пример использования array_key_exists()
Пример #2 array_key_exists() и isset()
Примечания
Смотрите также
User Contributed Notes 38 notes
If you want to take the performance advantage of isset() while keeping the NULL element correctly detected, use this:
Benchmark (100000 runs):
array_key_exists() : 205 ms
is_set() : 35ms
isset() || array_key_exists() : 48ms
Note:
The code for this check is very fast, so you shouldn’t warp the code into a single function like below, because the overhead of calling a function dominates the overall performance.
function array_check(. )
<
return (isset(..) || array_key_exists(. ))
>
You’ll notice several notes on this page stating that isset() is significantly faster than array_key_exists(). This may be true except for one small hitch. isset() will return false for arrays keys that have there value set to NULL, which is therefore not entirely accurate.
= array();
$foo [ ‘bar’ ] = NULL ;
Beware that if the array passed to array_key_exists is NULL, the return value will also be NULL.
This is undocumented behaviour, moreover the documentation (and return typehint) suggest that the array_key_exists function only returns boolean value. But that’s not the case.
The way array_key_exists handles null, float, boolean, and ‘integer-representing string’ keys is inconsistent in itself and, in the case of bool and float, with the way these are converted when used as array offset.
array (
» => 1,
0 => 2,
1 => 3,
4 => 4,
’08’ => 5,
8 => 6,
)
null is a key.
false is not a key.
true is not a key.
4.6 is not a key.
«08» is a key.
«8» is a key.
Well, and you get this warning three times (on the bools and the float, but not on the null):
Warning: array_key_exists() [function.array-key-exists]: The first argument should be either a string or an integer in /var/www/php/test.php on line 6
The argument of array_key_exists() vs. isset() came up in the workplace today, so I conducted a little benchmark to see which is faster:
?>
On Windows, the output is similar to
array_key_exists(): 0.504 [82.895%] seconds
isset(): 0.104 [17.105%] seconds
On Mac or Linux, isset() is faster but only by a factor of approximately 1.5.
I’ve got a new take on the multi key function I would like to share.
Very simple case-insensitive array_key_exists:
bool (in_array(strtolower($needle), array_map(‘strtolower’, array_keys($haystack))))
array_key_exists doesn’t work with objects implementing ArrayAccess interface. It also ignores possible __get() method in such objects, despite the fact it accepts object as a second parameter. It works only with ‘real’ properties.
Here is an example with array_key_exists switching between content-types :
I took hours for me to debug, and I finally recognized that,
Or you will get no reply.
Rudi’s multidimensional array_key_exists function was not working for me, so i built one that is.
Enjoy.
Here is a little function for case sensitivity to elaborate on what was said by MarkL from ##php (Freenode) and mmanning at mdanderson dot org from this page:
Also, I’ve been running into issues with escaping for Regex, so I decided to give something like this a shot:
Regarding performance differences between isset() and array_key_exists(), the differences may be there, but the function are not always interchangable.
A little function which take an array as keys
Here’s a function to return a reference to the first array element that has a given key. The code works for multidimensional arrays:
I created this function that uses array key exist to compare a form and a table to see if something has changed.
This can be very helpfull if you need to update a table record from a form but you do not want to display all table fields.
/// it works like array_key_exists that can go deeper
$cidade = array(
‘redonda’ => array(
‘curta’ => ‘o seu filme’
),
‘quadrada’ => array(
‘longa’ => array(
‘azul’ => array(‘logo’,2,’mais’,2,’são’,4),
‘amarela’ => array(‘então’,3,’vezes’,2,’são’,6),
‘verde’ => array(‘senão’,100,’dividido por’,2,’é’,50)
),
‘extravagante’ => array(
‘vermelha’ => ‘chama atenção’,
‘vinho’ => ‘cor de uva’,
‘ocre’ => 1255
),
‘comprida’ => array(
‘amarela’ => ‘brasilia dos mamonas’,
‘branca’ => ‘bandeira da paz’,
‘preta e branca’ => ‘peças do xadrez’
)
),
‘oval’ => array(
‘conde’ => ‘lobo’
),
‘plana’ => array(
‘curta’ => array(
‘azul’ => array(‘e’,2,’mais’,2,’são’,4),
‘amarela’ => array(‘sim’,3,’vezes’,2,’são’,6),
‘verde’ => array(‘verdade’,100,’dividido por’,2,’é’,50)
)
)
);
/// if the tree you search for exists, it will print out ‘true’
Further research on this has turned up that the performance problems are a known, confirmed bug in PHP 5.1.x, and have been fixed in PHP builds after September 2006. You can find the bug report here: http://bugs.php.net/bug.php?id=38812
However, just because it’s a fixed bug doesn’t really change the conclusion. If you’re writing a script and there’s any chance it could be used on a PHP 5.1.x server, you should still avoid this function and use isset() or some other kind of test if you want it to run efficiently.
I saw some examples above for array_keys_exist() or functions to see if multiple keys exist in a given array and return false if any of them don’t.
Here is a simpler way to do this:
array_keys
(PHP 4, PHP 5, PHP 7, PHP 8)
array_keys — Возвращает все или некоторое подмножество ключей массива
Описание
Список параметров
Массив, содержащий возвращаемые ключи.
Если указано, будут возвращены только ключи у которых значения элементов массива совпадают с этим параметром.
Определяет использование строгой проверки на равенство (===) при поиске.
Возвращаемые значения
Примеры
Пример #1 Пример использования array_keys()
Результат выполнения данного примера:
Смотрите также
User Contributed Notes 28 notes
It’s worth noting that if you have keys that are long integer, such as ‘329462291595’, they will be considered as such on a 64bits system, but will be of type string on a 32 bits system.
?>
will return on a 64 bits system:
but on a 32 bits system:
I hope it will save someone the huge headache I had 🙂
Here’s how to get the first key, the last key, the first value or the last value of a (hash) array without explicitly copying nor altering the original array:
Since 5.4 STRICT standards dictate that you cannot wrap array_keys in a function like array_shift that attempts to reference the array.
Invalid:
echo array_shift( array_keys( array(‘a’ => ‘apple’) ) );
But Wait! Since PHP (currently) allows you to break a reference by wrapping a variable in parentheses, you can currently use:
echo array_shift( ( array_keys( array(‘a’ => ‘apple’) ) ) );
However I would expect in time the PHP team will modify the rules of parentheses.
There’s a lot of multidimensional array_keys function out there, but each of them only merges all the keys in one flat array.
Here’s a way to find all the keys from a multidimensional array while keeping the array structure. An optional MAXIMUM DEPTH parameter can be set for testing purpose in case of very large arrays.
NOTE: If the sub element isn’t an array, it will be ignore.
output:
array(
‘Player’ => array(),
‘LevelSimulation’ => array(
‘Level’ => array(
‘City’ => array()
)
),
‘User’ => array()
)
array (size=4)
0 => string ‘e’ (length=1)
1 => int 1
2 => int 2
3 => int 0
—-
expected to see:
dude dude dude
Sorry for my english.
I wrote a function to get keys of arrays recursivelly.
Here’s a function I needed to collapse an array, in my case from a database query. It takes an array that contains key-value pairs and returns an array where they are actually the key and value.
?>
Example usage (pseudo-database code):
= db_query ( ‘SELECT name, value FROM properties’ );
/* This will return an array like so:
/* Now this array looks like:
?>
I found this handy for using with json_encode and am using it for my project http://squidby.com
This function will print all the keys of a multidimensional array in html tables.
It will help to debug when you don?t have control of depths.
An alternative to RQuadling at GMail dot com’s array_remove() function:
The position of an element.
One can apply array_keys twice to get the position of an element from its key. (This is the reverse of the function by cristianDOTzuddas.) E.g., the following may output «yes, we have bananas at position 0».
Hope this helps someone.
# array_keys() also return the key if it’s boolean but the boolean will return as 1 or 0. It will return empty if get NULL value as key. Consider the following array:
Array
(
[ 0 ] => first_index
[ 1 ] => 1
[ 2 ] => 0
[ 3 ] => 4
[ 4 ] => 08
[ 5 ] => 8
[ 6 ] =>
)
This function will extract keys from a multidimensional array
Array
(
[color] => Array
(
[1stcolor] => blue
[2ndcolor] => red
[3rdcolor] => green
)
[size] => Array
(
[0] => small
[1] => medium
[2] => large
)
Array
(
[0] => color
[1] => 1stcolor
[2] => 2ndcolor
[3] => 3rdcolor
[4] => size
[5] => 0
[6] => 1
[7] => 2
)
All the cool notes are gone from the site.
Here’s an example of how to get all the variables passed to your program using the method on this page. This prints them out so you can see what you are doing.
Simple ways to prefixing arrays;
[1] => Array
(
[product_id] => 2
[product_name] => Bar
)
I was looking for a function that deletes either integer keys or string keys (needed for my caching).
As I didn’t find a function I came up with my own solution.
I didn’t find the propiest function to post to so I will post it here, hope you find it useful.
?>
You can of course define constants to have a nicer look, I have chosen these: EXTR_INT = 1; EXTR_STRING = 2
EXTR_INT will return an array where keys are only integer while
EXTR_STRING will return an array where keys are only string
A needed a function to find the keys which contain part of a string, not equalling a string.