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?
Why does your code use
clone? Because otherwise it produces the same result asarray_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 whatarray_filter()does. The objects are not duplicated unless one usescloneto explicitly duplicate them.The PHP documentation page about objects mentions this behaviour: