|
php.net | support | documentation | report a bug | advanced search | search howto | statistics | random bug | login |
[2012-01-26 00:06 UTC] marc-bennewitz at arcor dot de
Description:
------------
On working with maps it's often needed to change the key of an existing element of an array, but it's currently not possible without a copy of the array or a unset + new element.
Test script:
---------------
// function to change the key
$arr = array('a' => 'a');
array_change_key($arr, 'a', 'b');
var_dump($arr);
echo PHP_EOL . '###########################################' . PHP_EOL;
// function to change the key (warning existing key)
$arr = array('a' => 'a', 'b' => 'b');
array_change_key($arr, 'a', 'b');
var_dump($arr);
echo PHP_EOL . '###########################################' . PHP_EOL;
// function to change the key (overwrite existing element)
$arr = array('a' => 'a', 'b' => 'b');
array_change_key($arr, 'a', 'b', true);
var_dump($arr);
echo PHP_EOL . '###########################################' . PHP_EOL;
// function to change the key (leave existing element)
$arr = array('a' => 'a', 'b' => 'b');
array_change_key($arr, 'a', 'b', false);
var_dump($arr);
echo PHP_EOL . '###########################################' . PHP_EOL;
// foreach key as ref
$arr = array('a' => 'a', 'b' => 'b');
foreach ($arr as &$k => $v) {
$k = 'b';
}
Expected result:
----------------
array(1) {
["b"]=>
string(1) "a"
}
###########################################
Warning: Can't change the array key 'a' to an already existing key 'b'
array(2) {
["a"]=>
string(1) "a",
["b"]=>
string(1) "b"
}
###########################################
array(1) {
["b"]=>
string(1) "a"
}
###########################################
array(1) {
["b"]=>
string(1) "b"
}
###########################################
Warning: Can't change the array key 'a' to an already existing key 'b'
array(2) {
["a"]=>
string(1) "a",
["b"]=>
string(1) "b"
}
Actual result:
--------------
Function related:
There is no funcation to change an array key
foreach related:
PHP Fatal error: Key element cannot be a reference
PatchesPull RequestsHistoryAllCommentsChangesGit/SVN commits
|
|||||||||||||||||||||||||||
Copyright © 2001-2025 The PHP GroupAll rights reserved. |
Last updated: Mon Nov 03 20:00:02 2025 UTC |
Your requested function can be written like this: function array_change_key(&$arr, $old, $new) { if (isset($arr[$new]) { trigger_error(...); } $arr[$new] = $arr[$old]; unset($arr[$old]); } This creates neither a copy of the array nor of the element ... due to copy on rite. And it's exactly hat we would do internally. PHP already has many array funtions and we won't add new ones which can be implemented easily in userland.