通过引用调用创建密钥索引

Calling a function which takes the parameter as a reference with an array with a key that does not exist, modifies the array so that the key exists later on.

function test(&$x)
{
}

$array = array();

print_r($array);
test($array['foo']);
print_r($array);

Array
(
)
Array
(
    [foo] => 
)

Why this happens and can I do something about it?

The key is created when you try to pass it to the function:

test($array['foo']);

You want to pass it by reference, so it has to exist. PHP will create it for you (but I guees it should throw a Notice if you have them enabled).

I would rewrite the function and pass the array and the key separately:

function test(&$array, $key)

and use it like this:

test($array, 'foo');