Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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?

share|improve this question

1 Answer 1

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

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.