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:

  1. <?php
  2. $a = array('a' => 1, 'b' => 2);
  3. $c = &$a['c'];
  4. print_r($a);
  5. ?>
  6. 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:

  1. Array
  2. (
  3. [a] => 1
  4. [b] => 2
  5. [c] =>
  6. )
  7. 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.

Back to top

Filed under PHP

Comments:

No comments have been added yet, you could be the first!

Leave a comment

RE: Quick PHP Tip: passing by reference creates array keys

Note to spammers: rel="nofollow" will be added to links. If I consider your comment spam, your IP-address might get blocked.

HTML not allowed. URLS will be auto-linked. Maximum length is 1250 characters.

I understand this is inconvenient, but the spam I'm receiving on this website is driving me nuts. Please forgive me and cope with it until I find a better solution.

Mandatory fields are marked by an asterisk (*).

Increase textarea-size Decrease textarea-size

Back to top

Preferences

These settings will be saved for your convenience.