1

I faced with a strange situation today. I need to change array element in foreach loop. As we know it can be done by using reference.

 foreach((array)$output['subjectComposite'] as &$subjectComposite){
     $subjectComposite['subjectSchemeVersion'] = $cellValue;
 }

But above code doesn't work and 'subjectSchemeVersion' is not set. At the same time if I remove (array) it works:

 foreach($output['subjectComposite'] as &$subjectComposite){
     $subjectComposite['subjectSchemeVersion'] = $cellValue;
 }  

Can you explain this behaviour to me?

1 Answer 1

3

By casting the $output variable to array, you make a copy of it. The & still works, but it refers to the copy. After the loop, the copy is forgotten/garbage collected, and the original $output was never changed.

You can do the following instead, this will convert $output to an array prior to the loop:

settype($output, 'array');
foreach($output['subjectComposite'] as &$subjectComposite){
    $subjectComposite['subjectSchemeVersion'] = $cellValue;
}
Sign up to request clarification or add additional context in comments.

1 Comment

Credit for the example goes to Nick J, he made a suggested edit :-)

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.