util (util) wrote in php_dev,
util
util
php_dev

getting reference to array value changes structure of array?

I'm surprised to see the var_dumps aren't identical. Is there any reason in practice to worry about the difference between them? Also, in general, is code like following frowned upon? I'm building up a data structure through reading rows from a database -- an array of arrays.
<?php

function &EmptyIfMissing(&$anArray, $key) {
  if (!array_key_exists($key, $anArray)) {
    $anArray[$key] = array();
  }
  return $anArray[$key];
}

$a = array();
$b = &EmptyIfMissing($a, 'B');
$b['C'] = 'C';
var_dump($a);
var_dump(array('B'=>array('C'=>'C')));
has output
array(1) {
  ["B"]=>
  &array(1) {
    ["C"]=>
    string(1) "C"
  }
}
array(1) {
  ["B"]=>
  array(1) {
    ["C"]=>
    string(1) "C"
  }
}
  • Post a new comment

    Error

    Anonymous comments are disabled in this journal

    default userpic

    Your IP address will be recorded 

  • 3 comments