Simple Gifts
Simple Gifts

Reputation: 51

php: stdclass array element changed after referencing element via pointer

folks. I've stumbled across an odd situation when referencing a standard class array element via pointer. This example is run on php 5.4.3, windows XP, Apache

$myLittleArray = array();
$myLittleArray[0] = new stdClass;
$myLittleArray[0]->fruit = 'apple';

$myLittleArray[1] = new stdClass;
$myLittleArray[1]->fruit = 'banana';

$myLittleArray[2] = new stdClass;
$mla = &$myLittleArray[2];
$mla->fruit = 'kiwi';

print_r($myLittleArray);   // $myLittleArray[2]->fruit  displays as "kiwi"

foreach ($myLittleArray as $mla){
   $mla->pricePerPound = 0.0;
}

print_r($myLittleArray);   // $myLittleArray[2]->fruit  displays as "banana" ???

first printr statement displays

Array
(
[0] => stdClass Object
    (
        [fruit] => apple
    )

[1] => stdClass Object
    (
        [fruit] => banana
    )

[2] => stdClass Object
    (
        [fruit] => kiwi
    )
}

second printr statement (note that $myLittleArray[2]->fruit has changed to "banana"

Array
(
[0] => stdClass Object
    (
        [fruit] => apple
        [pricePerPound] => 0
    )

[1] => stdClass Object
    (
        [fruit] => banana
        [pricePerPound] => 0
    )

[2] => stdClass Object
    (
        [fruit] => banana
        [pricePerPound] => 0
    )
)

*/

If I use a different variable name in the last foreach, say $mla1, the code works as expected ($myLittleArray[2]->fruit == 'kiwi'). Is this a php issue, or am I not looking at this correctly?

Upvotes: 1

Views: 54

Answers (1)

Barmar
Barmar

Reputation: 780984

It's because you previously made $mla a reference to $myLittleArray[2]. When foreach assigns to $mla each time through the loop, it's actually assigning to $myLittleArray[2]. So the first time through the loop it sets $myLittleArray[2] to a copy of $myLittleArray[0], and the second time it sets $myLittleArray[2] to a copy of $myLittleArray[1].

Upvotes: 2

Related Questions