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.

NoOne
  • 104
  • 12
Andrewboy
  • 364
  • 5
  • 15
  • https://stackoverflow.com/questions/29798586/php-an-iterator-cannot-be-used-with-foreach-by-reference – nerdlyist Sep 12 '18 at 16:28
  • Possible duplicate of [PHP Pass by reference in foreach](https://stackoverflow.com/questions/3307409/php-pass-by-reference-in-foreach) – Script47 Sep 12 '18 at 16:29
  • Can you attach dump of $ob array? – Maksym Fedorov Sep 12 '18 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. – Andrewboy Sep 12 '18 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. – nerdlyist Sep 12 '18 at 16:53
  • i add the object to the question – Andrewboy Sep 12 '18 at 17:05
  • I cannot reproduce your issue. Something is missing in this... – nerdlyist Sep 12 '18 at 17:31
  • Create a [mcve] that demonstrates this problem... – miken32 Sep 12 '18 at 17:48
  • Please post some complete code which is reproduceable. – Herwig Sep 12 '18 at 18:19

1 Answers1

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';