Home > Software engineering >  Why is array_filter returning a reference?
Why is array_filter returning a reference?

Time:11-17

I would like to understand the difference between these two ( $bookingRows is an array of objects with different properties).

$vehicleRows = [];
foreach($bookingRows as $row) {
 if($row->GroupCode == 'F') {
   $vehicleRows[] = clone $row;
 }
}

and

$vehicleRows = array_values(
 array_filter($bookingRows, function ($row) {
   return $row->GroupCode == 'F';
 })
);

My problem is that if I modify something in the $vehicleRows array, it reflects these changes in the origin, $bookingRows, as well -- which is not what I want. How can I avoid such an unwanted reference between the origin and the filtered set of items?

CodePudding user response:

Why does your code use clone? Because otherwise it produces the same result as array_filter().

array_filter() is not the culprit here, the PHP objects are manipulated through a handle. That handle is copied on assignments and this is what array_filter() does. The objects are not duplicated unless one uses clone to explicitly duplicate them.

The PHP documentation page about objects mentions this behaviour:

PHP treats objects in the same way as references or handles, meaning that each variable contains an object reference rather than a copy of the entire object. See Objects and References.

  • Related