note 104675 added to language.types.array
| From: | php_net at mcdragonsoftware dot com | Date: | Thu, 30 Jun 2011 01:16:54 +0000 |
| Subject: | note 104675 added to language.types.array | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-181083@lists.php.net to get a copy of this message | ||
//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
----
Server IP: 69.147.83.197
Probable Submitter: 67.0.0.130
----
Manual Page -- http://www.php.net/manual/en/language.types.array.php
Edit -- https://master.php.net/note/edit/104675
Del: integrated -- https://master.php.net/note/delete/104675/integrated
Del: useless -- https://master.php.net/note/delete/104675/useless
Del: bad code -- https://master.php.net/note/delete/104675/bad+code
Del: spam -- https://master.php.net/note/delete/104675/spam
Del: non-english -- https://master.php.net/note/delete/104675/non-english
Del: in docs -- https://master.php.net/note/delete/104675/in+docs
Del: other reasons-- https://master.php.net/note/delete/104675
Reject -- https://master.php.net/note/reject/104675
Search -- https://master.php.net/manage/user-notes.php