views:

81

answers:

3

Hi, I am sending a reference of an array variable which is initially empty. In the called function the array gets populated.

function one()
{
     $ret = array();
     two($ret);

      pri nt_r($ret);
}

function two(&$res)
{
     foreach($a as $b)
     {
       $id = $b->getid();
       $txt = $b->gettxt();

       $res[$id] = $txt;
      }
}

Here, if $id is duplicated i assume that it is by default overwritten. That is if the foreach runs for 5 times and for three times if id=5 then the result is only two elements in the array;

Is this the default behavior for this kind of assignment of arrays? or am i missing something?

+1  A: 

I don't understand why you are talking about arrays by reference, or what $a is in your example, but the simple answer is yes, they are overwritten.

$a = array();
$b = 'someText'; // or $b = 25;
$a[$b] = 1;
$a[$b] = 2;

Then $a[$b] will be 2, whatever $b is and, wherever $a comes from.

Colin Fine
Yes, thank you. this is the first time i am trying such code so i thought of getting comments form experts. Me too tested and it is overwriting.
Jayapal Chandran
Do i have to discard this post because the topic is not relevant. i shouldn't have added the word reference here.
Jayapal Chandran
A: 

Yes, it is overwriting the duplicates with the last values. I tested separately and it happened to be as assumed. But if we use array_push i hope it will be duplicated. I thought the direct assignment of duplicates will be duplicated instead of overwriting. anyway let me get some comments form the users so i can update if i am missing some useful information about this duplicating and overwriting.

Jayapal Chandran
Please do not provide additional details to your question as an answer. Stack Overflow is not a forum. [Edit your question instead](http://stackoverflow.com/posts/3492404/edit)
Gordon
Oh, ok. i will follow this.
Jayapal Chandran
+2  A: 

From the PHP Manual on Arrays:

An array in PHP is actually an ordered map. A map is a type that associates values to keys. This type is optimized for several different uses; it can be treated as an array, list (vector), hash table (an implementation of a map), dictionary, collection, stack, queue, and probably more. As array values can be other arrays, trees and multidimensional arrays are also possible.

Further

A key may be either an integer or a string. If a key is the standard representation of an integer, it will be interpreted as such (i.e. "8" will be interpreted as 8, while "08" will be interpreted as "08")

And most important for your question

If a key is not specified for a value, the maximum of the integer indices is taken and the new key will be that value plus 1. If a key that already has an assigned value is specified, that value will be overwritten.

Gordon
Nice. Thank you for this information.
Jayapal Chandran