PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!
<?php
class Obj
{
var $_num;
function Obj($num)
{
$this->_num = $num;
}
}
$array = array( 'one' => new Obj(1), 'two' => new Obj(2) );
$obj = &$array['three'];
print_r( $array );
/*
Output
Array ( [one] => obj Object ( [_num] => 1 ) [two] => obj Object ( [_num] => 2 ) [three] => )
*/
Why 'three' has been added?!?!? What is the correct way to do the referencing? The code may look weird but my key to the array element may be non-existant, in that case, I don't wish to have rubbish added to the array.
Thanks in advance.
?>
your reference setting implicitly adds the element to the array, because you may want to set stuff into it. You should use isset() to check if the element exists first, then make the reference. Otherwise, set it to null or something.
feyd wrote:your reference setting implicitly adds the element to the array, because you may want to set stuff into it. You should use isset() to check if the element exists first, then make the reference. Otherwise, set it to null or something.
Thanks for the response. You're right, after posting the question I saw another post from php.net stating what you said. I have to admit that the functionality is not very logical. The reference is on the RHS but anyways, I'll use isset(). Cheers.