[TYPO3-core] RFC #11876: stripSlashesOnArray creates references where you want copies

Ernesto Baschny [cron IT] ernst at cron-it.de
Tue Nov 3 18:41:11 CET 2009


Steffen Kamper schrieb:
> Hi Ernesto,
> 
> i read the patch (doesn't apply on trunk) and i read documentation here:
> http://www.php.net/manual/en/control-structures.foreach.php
> 
> I'm unsure about your patch as you unset inside foreach. Documentation
> says that "last" element stays, so unset has to be done outside foreach,
> see also the example there:
> $arr = array(1, 2, 3, 4);
> foreach ($arr as &$value) {
>     $value = $value * 2;
> }
> // $arr is now array(2, 4, 6, 8)
> unset($value); // break the reference with the last element
> 
> So could you verify this?


I did and this is not correct. Every element in the loop gets assigned a
reference. This is I consider a PHP bug, and I doubt that they will
document that. :)

Test this and uncomment the "unset" in the proper positions to see the
effect and that only the inside loop unset really trashes each reference.

<?
// Test function (from t3lib_div):
function addSlashesOnArray(array &$theArray)    {
        foreach ($theArray as &$value) {
                if (is_array($value)) {
                        addSlashesOnArray($value);
                } else {
                        $value = addslashes($value);
                }
		# inside loop
                #unset($value);
        }
	# outside loop
        #unset($value);
        reset($theArray);
}

// create some array with multiple values
$arr = array('a', 'b');
echo "orig:\n"; var_dump($arr);

// apply the
addSlashesOnArray($arr);

// make a copy of the array and modify first item (we expect it to apply
to copy only!):
$copy = $arr;
$copy[0] = 'X';

// not check if original was changed by the modification in the copy:
echo "\ncopy:\n"; var_dump($copy);
echo "\norig (should be the same as the orig):\n"; var_dump($arr);

?>


More information about the TYPO3-team-core mailing list