On Sat, 5 Apr 2003 09:40:19 +0300, you wrote:

>I tried something like this:
>
><?
>$arrayA = array(5,4,3,2,1);
>$arrayB = $arrayA;
>array_multisort($arrayA);
>echo $arrayA[0], "<br>";
>echo $arrayB[0];
>?>
>
>
>The output is:
>1
>1
>
>I think it should be:
>1
>5

It's not a bug (ie this is expected behaviour in PHP4 for various
sensible reasons), but it can sometimes throw up odd effects if you're
not expecting it.

What you're running into here is the difference between a deep copy
(make a copy of a piece of memory) and a shallow copy (make two
variables point to the same piece of memory).

The way to think of it is that $arrayA doesn't actually contain your
array values - it contains a reference (a pointer in C-speak) to the
memory location where the array values are stored. The line

$arrayB = $arrayA;

is copying the reference, not the values. You can run up against this
behaviour in quite a few of the post-C++ languages, and it can be
disconcerting if you're used to languages where copies are all deep
unless flagged otherwise.

To add insult to injury, some array operations can implicitly cause a
deep copy to be made. Try this, which adds one extra line:

<?
function echo_array($a) {
        foreach ($a as $v) {
                echo ($v);
                echo (', ');
        }
        echo ("<br>");
}
$arrayA = array(5,4,3,2,1);
$arrayB = $arrayA;
$arrayA[] = 6; // this line added
array_multisort($arrayA);
echo_array($arrayA);
echo_array($arrayB);
?>

More details (maybe) here:

http://www.zend.com/zend/art/ref-count.php


-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php

Reply via email to