0

I have the following issue: I would like to modify the elements of object. Accessing an element is working like:

foreach($ob as $element){echo $element->id;}

If I do the same

foreach($ob as $element){$element->id='XYZ';}

But this will not save into the object

I tried the following:

 foreach($ob as &$element){$element->id='XYZ';}

But in this case i got the following error:

An iterator cannot be used with foreach by reference

Actually the $ob is a cakephp Query object looks like:

    [
    (int) 0 => object(App\Model\Entity\Document) {
            'id' => (int) 26,'name'=>'Fax'}
(int) 1 => object(App\Model\Entity\Document) {
                'id' => (int) 26,'name'=>'Email'}
]

and I want to modify the id's.

Thank you for your help.

9
  • stackoverflow.com/questions/29798586/… Commented Sep 12, 2018 at 16:28
  • Possible duplicate of PHP Pass by reference in foreach Commented Sep 12, 2018 at 16:29
  • Can you attach dump of $ob array? Commented Sep 12, 2018 at 16:36
  • i can not attach the $op object since its too big. But this question must be general,i was trying to find solution here,also i found the above linked questions but non of them helped. Commented Sep 12, 2018 at 16:50
  • The issue is we do not know what you are trying to do (Problem) or what you are working with (Data). What you have is very general which makes the answers we can give very generalized and as you can see things we think were already solved on the site. Try and parse down your object so we can see it and then give us a case that you are trying to complete. Commented Sep 12, 2018 at 16:53

1 Answer 1

1

I work a lot with Arrays of Objects.
What best worked for me is the common for() Loop

$iobcount = count($ob);

for($iob = 0; $iob < $iobcount; $iob++)
  $ob[$iob]->id = 'XYZ';
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.