How to make a full copy of an array in PHP: assignment operator vs clone
Hello colleagues! I'm a beginner in PHP and encountered an unclear situation. I have an array with user data:
```php
$users = [
['name' => 'Ivan', 'age' => 25],
['name' => 'Maria', 'age' => 30]
];
```
I need to create its full copy so that I can modify data in the copy without affecting the original. I tried simple assignment:
```php
$usersCopy = $users;
$usersCopy[0]['name'] = 'Petr';
print_r($users[0]['name']); // Output "Petr", but I expected "Ivan"!
```
Why did the original change? I thought that in PHP arrays are copied on assignment. I tried using `clone`:
```php
$usersCopy = clone $users;
// But clone only works with objects, gives an error for arrays
```
Also I read about `array_copy()`, but such a function doesn't exist in PHP. Please tell me how to properly
No answers yet.
Log in to leave an answer
Blogs
Docker and TypeScript: Application Containerization for Developers