note 94578 deleted from function.unset by danbrown

From: Date: Thu, 12 Nov 2009 19:41:55 +0000
Subject: note 94578 deleted from function.unset by danbrown
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-162823@lists.php.net to get a copy of this message
Note Submitter: jlcadastros at gmail dot com ---- Here's some tests about unset and arrays. Please correct me if I'm wrong, but it seems that the only way to unset array elements using foreach is unsetting the original array. A NOTE on the foreach manual page: Note: Unless the array is referenced, foreach operates on a copy of the specified array and not the array itself. foreach has some side effects on the array pointer. Don't rely on the array pointer during or after the foreach without resetting it. It seems that even if we reference the array, its' content remain unchanged after an unset. Take a look at http://php.net/manual/en/language.references.unset.php and http://br.php.net/manual/en/control-structures.foreach.php Made with PHP 5.2.5 --- Code: <?php $array = array("Hello","World","!"); echo "Original".PHP_EOL; var_dump($array); echo "Changing Content not Using Reference".PHP_EOL; foreach ($array as $foo) { $foo .= "123"; } var_dump($array); echo "Changing Content Using Reference".PHP_EOL; foreach ($array as &$foo) { $foo .= "123"; } var_dump($array); echo "Unset Without Reference".PHP_EOL; foreach ($array as $foo) { unset($foo); } var_dump($array); echo "Unset With Reference".PHP_EOL; foreach ($array as &$foo) { unset($foo); } var_dump($array); echo "Unset from source".PHP_EOL; foreach ($array as $key => $foo) { unset($array[$key]); } var_dump($array);?> --- Outputs: Original array(3) { [0]=> string(5) "Hello" [1]=> string(5) "World" [2]=> string(1) "!" } Changing Content not Using Reference array(3) { [0]=> string(5) "Hello" [1]=> string(5) "World" [2]=> string(1) "!" } Changing Content Using Reference array(3) { [0]=> string(8) "Hello123" [1]=> string(8) "World123" [2]=> &string(4) "!123" } Unset Without Reference array(3) { [0]=> string(8) "Hello123" [1]=> string(8) "World123" [2]=> string(8) "Hello123" } Unset With Reference array(3) { [0]=> string(8) "Hello123" [1]=> string(8) "World123" [2]=> string(8) "Hello123" } Unset from source array(0) { }

« previous php.notes (#162823) next »