Question

How to Copy Arrays in PHP: Assignment, References, and Safe Copies

phparrayscopy

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.

Take Quiz

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();
$outsideItems = $basket->items;

$outsideItems[] = 'eggs';

print_r($basket->items);
print_r($outsideItems);

Here, $outsideItems is a separate array value.

Using a reference by mistake

$original = [1, 2, 3];
$copy = &$original;

$copy[0] = 999;

print_r($original); // [999, 2, 3]
print_r($copy);     // [999, 2, 3]

This is not a copy. It is a shared reference.

Copying nested arrays

A normal assignment also works for nested arrays:

$a = [
    'user' => ['name' => 'Sam'],
    'active' => true
];

$b = $a;
$b['user']['name'] = 'Alex';

print_r($a);
print_r($b);

In normal PHP array usage, $a remains unchanged after modifying $b.

When you may need extra care

If your array contains objects, the array itself is copied, but the object values inside it still refer to the same object instances.

class User {
    public string $name;

    public function __construct(string $name) {
        $this->name = $name;
    }
}

$a = ['user' => new User('Sam')];
$b = $a;

$b['user']->name = 'Alex';

echo $a['user']->name; // Alex

The array was copied, but the object inside was shared.

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.

2. Create an object

$config = new Config();

Now $config is an object with this array inside it:

[
    'theme' => 'dark',
    'language' => 'en'
]

3. Copy the array property

$localSettings = $config->settings;

This assigns the array value to $localSettings. In normal PHP usage, this behaves as a copy.

4. Change the new variable

$localSettings['theme'] = 'light';

Only $localSettings is changed.

5. Print both arrays

print_r($config->settings);
print_r($localSettings);

Result:

Array
(
    [theme] => dark
    [language] => en
)

Array
(
    [theme] => light
    [language] => en
)

The object property stays the same because you copied the array value rather than creating a reference.

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.

Take Quiz

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

$config = $defaultConfig;
$config['host'] = $userConfig['host'] ?? $config['host'];

Important real-world warning

If the array contains objects, resources, or references, the copy may not behave like a fully independent deep clone. In those cases, developers may need custom copying logic.

For plain arrays of strings, numbers, booleans, and nested arrays, normal assignment is usually exactly what you want.

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 = ['user' => new stdClass()];
$a['user']->name = 'Sam';

$b = $a;
$b['user']->name = 'Alex';

echo $a['user']->name; // Alex

The array was copied, but the object instance inside it was not cloned.

Avoid this by cloning objects when needed.

4. Mixing references into loops

This can cause confusing behavior:

foreach ($array as &$value) {
    $value = strtoupper($value);
}

If you use references in foreach, be careful to unset the reference afterward:

unset($value);

5. Assuming object assignment works the same as array assignment

$obj2 = $obj1;

This does not create an independent copy of the object. Objects are handled differently from arrays in PHP. Use clone if you need a separate object.

Comparisons

ConceptSyntaxResultWhen to use
Array copy by value$b = $a;Independent array valueNormal array copying
Reference assignment$b = &$a;Both variables share the same valueRare cases where shared mutation is intended
Object assignment$obj2 = $obj1;Both variables refer to the same objectWhen you want to work with the same object
Object cloning$obj2 = clone $obj1;New object instanceWhen you need a separate object

Arrays vs objects in PHP

  • Arrays: assignment normally behaves like copying the value
  • Objects: assignment shares the same object instance

Assignment vs reference

$a = [1, 2, 3];
$b = $a;   // copy
$c = &$a;  // reference
  • Changing $b does not change $a
  • Changing $c does change $a
Take Quiz

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

$copy = $original;
$copy['new_key'] = 'value';
$data = $obj->data;
unset($data['secret']);
$options = $defaults;
$options['timeout'] = 30;

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.

Take Quiz

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

  1. Create a class with one array property.
  2. Instantiate the class and assign its array property to a new variable.
  3. Modify the new variable without using references.
  4. Print both the original object property and the copied array.
  5. Add a second example that uses a reference and shows the difference.
Take Quiz

Keep learning

Related questions

View more