How to clone variable in PHP?

Problem understanding it? Stick to the article until the end to learn about this example and much more about array cloning in PHP.

Introduction

There are many ways to copy an array in PHP. However, there are two important terminologies to understand before jumping into the examples. These terminologies are deep copy and shallow copy.

Let’s understand these and then move on to the practical stuff.

Deep Copy PHP Arrays Examples

A deep copy is an array clone with a unique reference and dedicated space in memory. Let’s assume array B is a copy of array A. Just because it is a deep copy, thus changing array B doesn’t affect array A.

How to clone variable in PHP?

Shallow Copy

A shallow copy is an array clone with shared reference and memory space. Let’s assume array B is a copy of array A. Just because it is a shallow copy with shared reference and memory, thus changing array B affects array A.

How to clone variable in PHP?

How to copy array in PHP – Assign a copy.

PHP makes a deep copy of an array using the assignment operator. It is just as simple as assigning one variable to another. Here’s how.

<?php
 
$programming_languages = ['PHP', 'Python', 'Javascript'];
 
$programming_languages_clone = $programming_languages;
 
$programming_languages_clone[] = 'Java';
 
//$programming_languages = [PHP, Python, Javascript]
//$programming_languages_clone = [PHP, Python, Javascript, Java]
 
?>

Adding ‘Java’ to the cloned array doesn’t affect the original array. 

How to copy array in PHP – Using array_merge

PHP array_merge is also helpful in creating a deep copy of an array. Let’s revisit the above example.

<?php
 
$programming_languages = ['PHP', 'Python', 'Javascript'];
 
$programming_languages_clone = array_merge([],$programming_languages);
 
$programming_languages_clone[] = 'Java';
 
//$programming_languages = [PHP, Python, Javascript]
//$programming_languages_clone = [PHP, Python, Javascript, Java]
 
?>

The array_merge fuses an empty array with the programming_languages array and returns a new array, a deep copy.

How to copy array in PHP – Assign a reference

Let’s see how to make a shallow copy of an array in PHP. As seen already, a shallow copy shares the reference and memory space. So, all we need is to assign the reference to a new variable. Think of a reference as a pointer to the exact memory location of the original array.

<?php
 
$programming_languages = ['PHP', 'Python', 'Javascript'];
 
$programming_languages_clone = &$programming_languages;
 
$programming_languages_clone[] = 'Java';
 
//$programming_languages = [PHP, Python, Javascript, Java]
//$programming_languages_clone = [PHP, Python, Javascript, Java]
 
?>

The & in PHP is for assigning a reference than a copy. As the clone is a shallow copy, changing it affects the original because they both point to the same array residing in the same memory space.

How to copy array of objects in PHP – Using array_map

Objects are always passed by reference. So contrary to the first example for array copy, assigning one object to another is always by reference. A way out is using the clone keyword.

$employee_1 = new Employee('1', 'Allen', 60000, '29');
$employee_2 = clone $employee_1;

Cloning an array of objects is complicated because the objects always share references.

How to clone variable in PHP?

The array is a deep copy, but the object is still a shallow copy. The following example uses the array_map function to make a deep clone of an array of objects.

$employees_arr =
[
    new Employee('5', 'Brian', 90000, '25'),
    new Employee('1', 'Allen', 60000, '29'),
    new Employee('2', 'Kylie', 50000, '27'),
    new Employee('3', 'Jeane', 80000, '35'),
    new Employee('4', 'Franklin', 75000, '30'),
];
 
 
$employees_arr_clone = array_map(function($obj) {return clone $obj;},$employees_arr);

The array_map function returns an array of deeply cloned objects. 

How to copy multidimensional array in PHP

A multidimensional array takes complexity to the next level. It is challenging in a way that it can include many levels of subarrays and varying data types. We need a robust code, one ring to rule them all. So, a recursive function is a way to go.

function clone_array($arr) {
    $clone = array();
    foreach($arr as $k => $v) {
        if(is_array($v)) $clone[$k] = clone_array($v); //If a subarray
        else if(is_object($v)) $clone[$k] = clone $v; //If an object
        else $clone[$k] = $v; //Other primitive types.
    }
    return $clone;
}

This function is robust enough to handle all kinds of arrays. Here’s how it works.

  • It traverses the array and checks the type of elements.
  • If the element is an array, it recursively calls the function to repeat the logic.
  • If the element is an object, it makes a clone, a deep copy.
  • Else, for the primitive type, it just assigns it to the key.

That’s all about it. We have pretty much seen all about array cloning in PHP.

PHP Fundamentals Recommendations

This article is part of our content on PHP Fundamentals. It includes the core concepts that build upon the foundation of writing high-quality PHP code. If you are looking to grow your PHP development abilities. Check out the following recommended affiliate resources. We do make a commission if you do choose to buy through our links. It is one of the ways that help support our mission here at FuelingPHP.

Book: Fundamentals of Web Development

How to clone variable in PHP?

This book is for you if you are starting to learn how to build websites. It is more than just an “intro to programming” book. You will learn the concepts and tips on what goes into creating a high-quality website. Today’s websites are more than text on a screen. They are highly complex applications that encourage user experience. Learn the fundamentals of good web development with this book.

Check it out on Amazon

Book: Programming in PHP (O’Reilly)

How to clone variable in PHP?

O’Reilly should not need any introduction. They are the top publishers when it comes to books on programming and technology. This book fits well within their vast library. If you are newer to the PHP language or want to keep a solid reference by your side. I highly recommend this book for your collection.

Check it out on Amazon

Book: Design Patterns in PHP

How to clone variable in PHP?

I highly recommend this book to any intermediate-level web developer. It takes the theories and best practices of writing high-quality code via design patterns and applies them to PHP. It is a great resource to take your career to the next level

Check it out on Amazon

Video Course: PHP Fundamentals (Pluralsight)

How to clone variable in PHP?

Want to quickly learn PHP? This PHP Fundamentals course is ideal for beginner PHP developers. It is a deep dive into the concepts, structures and well “fundamentals” of PHP development. It includes high-quality video & interactive resources that teach you really fast. I highly recommend this if you are getting started in your PHP journey.

Click here for a 10-day free trial to Pluralsight

Complete Learning Path: Web Development (Pluralsight)

How to clone variable in PHP?

You should definitely check out this learning path from Pluralsight. They have a huge list of video courses, training, and interactive lessons on growing your web development career. You get access to the full library of hundreds of resources for a single monthly subscription. It truly is like Netflix for your career.

Click here to see details (10-day free trial included)

Copying Arrays using PHP

The article explores how to copy array in PHP. It starts with differentiating deep copy and shallow copy. Following that section, it includes several ways to make an array clone. Following this, we see how to make a clone of an array of objects. Finally, we create one ring to rule them all, and that’s the last function we have just seen.

Hopefully, you’ve enjoyed the article. Stay tuned for more articles like these at FuelingPHP.

Want to learn more about PHP?

We have many fun articles related to PHP. You can explore these to learn more about PHP.

  • How to push item to the first index of array PHP
  • Intro into Symfony Doctrine PHP ArrayCollection
  • How to split a multidimensional array in PHP
How to clone variable in PHP?

How to clone variable in PHP?
15+ Array of Objects PHP Code Examples | 2023 Tutorial
How to clone variable in PHP?
How to Filter Arrays in PHP with array_filter() Code Examples
How to clone variable in PHP?
What is an associative array or hash map in PHP
How to clone variable in PHP?
POST cURL Body from File: PHP Code Examples ( JSON, CSV )


  • ← Best ways to store PHP arrays to data sources
  • 3 Push elements in a multidimensional array PHP code examples →

Write Better Code Faster

Click here to get our 'Become a Rockstar PHP Dev in 7 Days' top secrets delivered to your inbox.

sign up

How to clone variable in PHP?

Stephen Miracle

Hey! I hope you enjoyed this article. I have been professionally developing websites & software for well over 20 years. I started FuelingPHP as a way to give back to the open-source community that helped me be able to live comfortably building things I love.

How to copy variable value in PHP?

The value of the object variable can be copied to another variable in PHP by using object cloning. In PHP, a shallow copy of the object can be created by using the keyword clone, and a deep copy of the object can be created by using the method __clone().

How to create clone of object in PHP?

An object copy is created by using the clone keyword (which calls the object's __clone() method if possible). $copy_of_object = clone $object; When an object is cloned, PHP will perform a shallow copy of all of the object's properties. Any properties that are references to other variables will remain references.

What is the use of clone () method?

The clone() method is used to create a copy of an object of a class which implements Cloneable interface. By default, it does field-by-field copy as the Object class doesn't have any idea about the members of the particular class whose objects call this method.

How to copy a string in PHP?

PHP - Function copy() The copy() function makes a copy of the source file to the destination, and it returns true on success or false on failure.