SitePoint Sponsor

User Tag List

Results 1 to 2 of 2
  1. #1
    SitePoint Member
    Join Date
    Jul 2011
    Posts
    8
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    array seems to be copied by reference

    From what I can find about PHP copying arrays, arrays are supposed to be copied by value. This may be where I'm mistaken, but I interpret "copied by value" as a new array will be created with the same keys/values, etc. In the following simplified code, which is taken from a recursive function, it is apparent to me that the array is being copied by reference:
    Code:
    $aresult = array();
    $stmt->bind_result($aresult['constraint'], $aresult['table'], $aresult['column'], $aresult['refTable'], $aresult['refColumn']);
    while ($stmt->fetch())
    {
       $accumulatingArray[] = $aresult;
       $tablesArray[] = $aresult['table'];
    }
    (I think this is enough information to explain my issue. I can add the surrounding code and output later if further discussion requires it.)

    Comparing the arrays, I would expect that each element of $accumulatingArray would be an array whose 'table' value matches the correspondingly-indexed value in $tablesArray. However, in $accumulatingArray, there are multiple (based on times through the "while" loop) "copies" of the same array for each time through this code fragment, while the $tablesArray shows (mostly) unique table names.

    That the $aresult changes each time through the "while" loop is the point of using bind_result(), but I want to save the array each time. I suppose I could try copying the $stmt->bind_result() statement to the bottom of the "while" loop to ensure a new array is used for each iteration. Event if that works, I still want to understand what is happening, if it's a bug or feature, and if there is a built-in PHP pattern to ensure I get a copy of the array.

    Thanks,
    Chuck Jungmann

  2. #2
    SitePoint Member
    Join Date
    Nov 2011
    Posts
    13
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    I looked at the function refernce on php.net (http://uk3.php.net/manual/en/mysqli-...ind-result.php) and it seems this method will pass by reference. But normal PHP behaviour is to pass by value.


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •