-
Notifications
You must be signed in to change notification settings - Fork 8k
Description
Description
The following code:
$data = array(
'testItem' => array(
'Test 1',
'Test 2',
'Test 3'
)
);
function format($someArray){
$someArray['testItem'] = 'test';
}
var_dump($data);
$item = &$data['testItem'];
format($data);
unset($item);
var_dump($data);
Resulted in this output:
array(1) {
["testItem"]=>
array(3) {
[0]=>
string(6) "Test 1"
[1]=>
string(6) "Test 2"
[2]=>
string(6) "Test 3"
}
}
array(1) {
["testItem"]=>
string(4) "test"
}
But I expected this output instead:
array(1) {
["testItem"]=>
array(1) {
["subItem"]=>
array(3) {
[0]=>
string(6) "Test 1"
[1]=>
string(6) "Test 2"
[2]=>
string(6) "Test 3"
}
}
}
array(1) {
["testItem"]=>
array(1) {
["subItem"]=>
array(3) {
[0]=>
string(6) "Test 1"
[1]=>
string(6) "Test 2"
[2]=>
string(6) "Test 3"
}
}
}
This does seem like a very specific case but it's one that I've just run into and spent way too long debugging.
The array is being passed to the function by value but the function is still somehow modifying the original array as if it were passed by reference.
It only happens if there's already a reference to the item in the array before it's passed to the function.
This can be a specific reference as in the test code above or by using foreach($data as &$item){.
If the reference is unset() before calling the function then it works as expected.
It only happens when the function changes elements in the array.
For example: $someArray = false; works as expected and doesn't overwrite anything in $data.
PHP Version
PHP 8.2.26
Operating System
Rocky Linux 9.3 (Blue Onyx)