Quick PHP Tip: passing by reference creates array keys
Posted on 29 April 2009 (06:35 PM)
Another little PHP tip that could save you a couple of debugging hours.
Consider the following code, and notice I use the ampersand character to fetch the value by reference:
<?php$a = array('a' => 1, 'b' => 2);$c = &$a['c'];print_r($a);?>- Download this code: /code/passing-by-reference-creates-array-keys1.txt
Shockingly, this won't give you a notice or warning. Instead, it'll output this array:
Array([a] => 1[b] => 2[c] =>)- Download this code: /code/passing-by-reference-creates-array-keys2.txt
This might have disastrous results, if your code works with those array keys one way or another. So be warned, and learn to love functions such as array_key_exists and empty.
Filed under PHP
- ← previous article: Quick PHP Tip: close your connection between stream_get_contents calls
- → next article: Move current selection to new folder with Applescript
Comments:
No comments have been added yet, you could be the first!