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!

Sorry, due to spam, comments are temporarily out of order.

Back to top

Preferences

These settings will be saved for your convenience.