Page 1 of 1

[Q] How to assign an array element to a variable by referenc

Posted: Wed Apr 20, 2005 4:12 pm
by raminhaeri
Hi,

I don't know if this is a bug or I'm doing something wrong! I'm using PHP4 and have the following code:

Code: Select all

<?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.
?>

feyd | Please review how to post code using

Code: Select all

and

Code: Select all

tags. Read:  [url=http://forums.devnetwork.net/viewtopic.php?t=21171]Posting Code in the Forums[/url][/color]

Posted: Wed Apr 20, 2005 5:55 pm
by feyd
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.

Posted: Wed Apr 20, 2005 10:54 pm
by raminhaeri
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.