A quick and dirty answer, but remember that calling this function with a link is outdated and may (depending on your php configuration) generate a warning:
array_splice($arr, 1, 0, array(&$var2));
Response to impressions and answers: what happens is pretty subtle. When you do the splice because you inserted the link at this position, $ var2 is really reassigned. You can check it with the following code:
<?php $hi = "test"; $var2 = "next"; $arr = array(&$hi); $arr[] = &$var2; // this works printf("=== var2 before splice:\n%s\n", var_export($var2, TRUE)); array_splice($arr, 1, 0, &$var2); // this doesn't printf("=== var2 after splice:\n%s\n", var_export($var2, TRUE)); ?>
You will get the following result:
=== var2 before splice: 'next' === var2 after splice: array ( 0 => 'next', )
Note that before splice, the string $ var2 was a string, as expected ("next"). However, after splicing, $ var2 was replaced by an array containing one element, the string "next".
I think the reason for this is because the documentation says: "If the replacement is not an array, it will look with one parameter (for example ((array) $"). So what happens:
- You pass & $ var2 to the array as a replacement.
- Internally, php will convert & $ var2 to an array (& $ var2). Actually, this can do something equivalent to $ param = array ($ param), which means that & $ var2 will be set to an array (& $ var2), and since this is a link, not a copy of $ var2 like this usually will, this affects a variable that usually goes beyond the scope of the call.
- Now he moves this new value of $ var2 to the end position and inserts a copy of $ var2 into the second position.
I'm not sure for sure that all the magic happens inside, but $ var is definitely reassigned during splicing. Note that if you use a third variable, because it does not assign something to something that already exists as a reference, it works as expected:
<?php $hi = "test"; $var2 = "next"; $var3 = "last"; $arr = array(&$hi); $arr[] = &$var2; // this works array_splice($arr, 1, 0, &$var3); printf("=== arr is now\n%s\n", var_export($arr, TRUE)); ?>
Generates the result:
=== arr is now array ( 0 => 'test', 1 => 'last', 2 => 'next', )