Skip to content

Instantly share code, notes, and snippets.

@svandragt
Last active February 7, 2022 09:10
Show Gist options
  • Select an option

  • Save svandragt/54ed37d93ef552dc50ea959590fc7afa to your computer and use it in GitHub Desktop.

Select an option

Save svandragt/54ed37d93ef552dc50ea959590fc7afa to your computer and use it in GitHub Desktop.
Gotcha: Iterated lists of objects pass by reference in PHP!
<?php
// won't be incremented
$a = [
0,
0,
];
// !! will be incremented !!
$b = [
(object)['count' => 0],
(object)['count' => 0],
];
foreach ($a as $i) { $i++; }
foreach ($b as $o) { $o->count++; }
var_dump($a, $b);
@svandragt

svandragt commented Feb 7, 2022

Copy link
Copy Markdown
Author

output:

array(2) {
  [0]=>
  int(0)
  [1]=>
  int(0)
}


array(2) {
  [0]=>
  object(stdClass)#1 (1) {
    ["count"]=>
    int(1)
  }
  [1]=>
  object(stdClass)#2 (1) {
    ["count"]=>
    int(1)
  }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment