note 104675 deleted from language.types.array by danbrown

From: Date: Thu, 30 Jun 2011 13:37:27 +0000
Subject: note 104675 deleted from language.types.array by danbrown
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-181098@lists.php.net to get a copy of this message
Note Submitter: php_net at mcdragonsoftware dot com ---- //unexpected behavior when passing pre-defined arrays with null elements to a function... function do_something_with_an_array( $ARRAY ) { return $ARRAY; } //a word of warning... $ARRAY = array( 'key1'=> 'val1', 'key2'=>null, 'key3'=> 'val3' ); $result = do_something_with_an_array( $ARRAY ); print_r( $result ); --- output: --------- array ( 'key1' => 'val1', 'key3' => 'val3' ) --------------------- //is not the same as... $result = do_something_with_an_array( array( 'key1'=> 'val1', 'key2'=>null, 'key3'=> 'val3' ) ); print_r( $result ); --- output: --------- array ( 'key1' => 'val1', 'key2' => null, 'key3' => 'val3', ) --------------------- //the difference is the first will DROP the null element from the array before the function gets it where the second will PRESERVE the array structure //why is this important? I use a function like this to serialize the $_GET to a url query string... the $ARRAY I pass contains the changes to make to the values, I often use this to remove elements by merging the $_GET & $ARRAY with null value elements in the $ARRAY //if these elements are destroyed in passing the arguments then I cannot remove an argument from the url //why don't I just unset($_GET['key2']) ? because I want to preserve the $_GET for use further in the code

« previous php.notes (#181098) next »