Question
In PHP, is there a built-in function for copying one array into another?
I have run into problems a few times when trying to copy arrays. Specifically, I want to take an array stored inside an object and copy it into another variable outside the object, without accidentally linking the two variables together.
Short Answer
By the end of this page, you will understand how array copying works in PHP, when a simple assignment is enough, how references can cause unexpected behavior, and how to safely copy arrays from objects into other variables.
Concept
In PHP, arrays are usually copied by value, which means assigning one array variable to another typically gives you a separate copy.
$a = [1, 2, 3];
$b = $a;
After this, $b starts with the same contents as $a. If you later change $b, $a will normally stay unchanged.
$b[0] = 99;
print_r($a); // [1, 2, 3]
print_r($b); // [99, 2, 3]
So in most cases, you do not need a special function to copy an array in PHP. A normal assignment is enough.
Why this matters
Many beginners expect arrays to behave like references automatically, especially when arrays come from objects, functions, or nested structures. The confusion usually comes from references, not from arrays themselves.
For example, if you use &, you are creating a reference:
$a = [1, 2, 3];
$b = &$a;
Now $a and $b point to the same underlying value. Changing one changes the other.
Important detail: copy-on-write
Internally, PHP uses an optimization called copy-on-write. This means PHP may delay making a real physical copy until one of the variables is changed. For everyday coding, the main rule is still simple:
$b = $a;gives you independent array values$b = &$a;makes them references to the same value
Arrays inside objects
If an object has an array property, you can copy it the same way:
$outside = $obj->items;
That gives $outside the array value. Unless references are involved, changing $outside will not change $obj->items.
This is the core idea behind the original question.
Mental Model
Think of a PHP array like a document.
- Normal assignment (
$b = $a) is like making a photocopy of the document. - Reference assignment (
$b = &$a) is like giving two people access to the same document on the same desk.
If you write on the photocopy, the original stays the same. If two people share the same document, any change is visible to both.
When arrays are stored inside objects, the same idea applies. Reading the array property and assigning it to another variable is usually just making a separate usable copy of the contents.
Syntax and Examples
Basic array copy
In PHP, the normal way to copy an array is simple assignment:
$original = ['apple', 'banana', 'orange'];
$copy = $original;
$copy[] = 'grape';
print_r($original);
print_r($copy);
Output:
Array
(
[0] => apple
[1] => banana
[2] => orange
)
Array
(
[0] => apple
[1] => banana
[2] => orange
[3] => grape
)
The original array is unchanged.
Copying an array from an object
class Basket {
public array $items = ['milk', 'bread'];
}
$basket = new Basket();
= ->items;
[] = ;
(->items);
();
Step by Step Execution
Consider this example:
class Config {
public array $settings = [
'theme' => 'dark',
'language' => 'en'
];
}
$config = new Config();
$localSettings = $config->settings;
$localSettings['theme'] = 'light';
print_r($config->settings);
print_r($localSettings);
Step by step
1. Define the class
class Config {
public array $settings = [
'theme' => 'dark',
'language' => 'en'
];
}
A class named Config is created. It has one property: $settings, which is an array.
Real World Use Cases
Working with configuration data
You may copy an array from an object, modify it locally, and keep the original configuration unchanged.
$runtimeConfig = $app->config;
$runtimeConfig['debug'] = true;
Preparing API responses
A controller may copy data from a model, then add or remove fields before returning JSON.
$response = $user->data;
unset($response['password']);
$response['is_online'] = true;
Form processing
You may copy submitted data, sanitize the copy, and keep the original request data unchanged for logging.
$cleanInput = $_POST;
$cleanInput['email'] = trim($cleanInput['email']);
Data transformation pipelines
When processing arrays through multiple steps, developers often copy the current state so each step can safely modify its own version.
Testing
In tests, it is common to copy sample input data and tweak only the fields needed for a specific test case.
Real Codebase Usage
In real PHP projects, developers usually rely on plain assignment for array copying.
Common patterns
Local modification of object data
$data = $order->payload;
$data['processed_at'] = date('c');
This lets code work with a modifiable copy.
Validation before saving
$data = $requestData;
if (!isset($data['email'])) {
throw new InvalidArgumentException('Email is required.');
}
The original input can remain untouched while validation and cleanup happen on the copied array.
Guarding against accidental mutation
Developers often copy arrays before passing them into code that may modify them.
$options = $defaultOptions;
$options['timeout'] = 5;
Merging defaults with user input
Common Mistakes
1. Thinking a special copy function is required
Broken assumption:
$copy = array_copy($original); // No such built-in function
Fix:
$copy = $original;
For standard PHP arrays, assignment is the normal copy operation.
2. Accidentally creating a reference
Broken code:
$copy = &$original;
$copy['x'] = 10;
Now both variables change together.
Fix:
$copy = $original;
$copy['x'] = 10;
Only $copy changes.
3. Forgetting that objects inside arrays are shared
Broken expectation:
$a = [ => ()];
[]->name = ;
= ;
[]->name = ;
[]->name;
Comparisons
| Concept | Syntax | Result | When to use |
|---|---|---|---|
| Array copy by value | $b = $a; | Independent array value | Normal array copying |
| Reference assignment | $b = &$a; | Both variables share the same value | Rare cases where shared mutation is intended |
| Object assignment | $obj2 = $obj1; | Both variables refer to the same object | When you want to work with the same object |
| Object cloning | $obj2 = clone $obj1; | New object instance | When you need a separate object |
Arrays vs objects in PHP
- Arrays: assignment normally behaves like copying the value
Cheat Sheet
Quick rules
- Copy an array with:
$copy = $original;
- Create a reference with:
$copy = &$original;
- Copying an array property from an object:
$outside = $obj->myArray;
Key facts
- PHP arrays are normally assigned by value
- PHP uses copy-on-write internally
- You usually do not need a special function to copy arrays
- If an array contains objects, the objects inside are still shared unless cloned
Safe default
If you want a separate array, use normal assignment and avoid &.
Watch out for
&creates references- Objects behave differently from arrays
foreach ($array as &$value)can leave behind a reference if not cleaned up
Common patterns
= ;
[] = ;
FAQ
Do I need a built-in function to copy an array in PHP?
No. In most cases, simple assignment is enough:
$copy = $original;
If I copy an array from an object, will changes affect the original?
Usually no, as long as you use normal assignment and not references.
What does & mean when copying arrays in PHP?
It creates a reference, not a separate copy. Both variables will point to the same value.
Why did changing my copied array also change the original?
The most common reasons are:
- You used
& - The array contains objects
- A reference was introduced earlier in the code
Are nested arrays copied too?
Yes, normal nested arrays are handled correctly with assignment.
Are objects inside arrays copied automatically?
No. The array structure is copied, but object instances inside it are still shared.
How do I make a deep copy in PHP?
For plain arrays, assignment is usually enough. If your array contains objects, you need custom logic or explicit clone operations for those objects.
Mini Project
Description
Build a small PHP script that copies an array from an object, modifies the copied version, and proves that the original array remains unchanged. This demonstrates the difference between normal assignment and reference assignment in a practical way.
Goal
Create a script that safely copies an array property from an object and shows the result before and after modification.
Requirements
- Create a class with one array property.
- Instantiate the class and assign its array property to a new variable.
- Modify the new variable without using references.
- Print both the original object property and the copied array.
- Add a second example that uses a reference and shows the difference.
Keep learning
Related questions
Are PDO Prepared Statements Enough to Prevent SQL Injection in PHP?
Learn how PDO prepared statements prevent SQL injection in PHP, what they protect, and the mistakes that still leave MySQL apps vulnerable.
Can You Bind an Array to an IN Clause in PHP PDO?
Learn how PDO handles placeholders in IN() clauses, why arrays cannot be bound directly, and the safe PHP pattern to build dynamic queries.
Choosing the Right MySQL Collation for PHP and UTF-8
Learn how MySQL character sets and collations work with PHP, and how to choose a practical UTF-8 setup for web applications.