note 94578 added to function.unset

From: Date: Thu, 12 Nov 2009 19:41:06 +0000
Subject: note 94578 added to function.unset
Groups: php.notes 
Request: Send a blank email to php-notes+get-162822@lists.php.net to get a copy of this message
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) { } ---- Server IP: 187.16.23.134 Probable Submitter: 200.169.41.21 ---- Manual Page -- http://www.php.net/manual/en/function.unset.php Edit -- https://master.php.net/note/edit/94578 Del: integrated -- https://master.php.net/note/delete/94578/integrated Del: useless -- https://master.php.net/note/delete/94578/useless Del: bad code -- https://master.php.net/note/delete/94578/bad+code Del: spam -- https://master.php.net/note/delete/94578/spam Del: non-english -- https://master.php.net/note/delete/94578/non-english Del: in docs -- https://master.php.net/note/delete/94578/in+docs Del: other reasons-- https://master.php.net/note/delete/94578 Reject -- https://master.php.net/note/reject/94578 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#162822) next »