1

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?

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.