Php copy with replace

PHP Array Copy & Clone (8 Methods)

PHP array copy or clone is an action to duplicate a PHP array (deep copy and shallow copy). This clone can be done in many ways such as = operator, pointer, ArrayObject class, and user-defined function to copy an array with subarray in PHP.

When working with arrays in PHP, you may need to create a duplicate of an existing array. This is where the array copy comes in. There are several built-in PHP functions to copy arrays in PHP too.

PHP deep copy and shallow copy of an array

A deep copy is an array clone with a unique reference and dedicated space in memory. A deep copy of an array in PHP is a copy of an array that contains all the elements of the original array and any additional elements that are contained within the original array.

Читайте также:  Java inputstream get filename

A shallow copy is an array clone with shared reference and memory space. A shallow copy of an array in PHP is a copy of an array that only copies the values of the array elements, not the references. This means that if the original array contains objects, the shallow copy will contain references to the same objects.

A deep copy of an array is different from a shallow copy, which only copies the elements of the original array and does not include any additional elements.

1. How to clone an array in PHP by = operator

In PHP, all variables except objects are assigned by the copy-on-write mechanism, while things are assigned by reference. This means that for the arrays with scalar values simply by = operand. This method is a deep copy.

$cars=array('fer'=>'Ferrari','ben'=>'Benz','bmw'=>'BMW'); $cars2=$cars; var_dump($cars2);
array (size=3) 'fer' => string 'Ferrari' (length=7) 'ben' => string 'Benz' (length=4) 'bmw' => string 'BMW' (length=3)

You need to just assign them to another variable to get a copy of that array.

2. By pointer

In the previous section, you have 2 different arrays with the same keys and values. But if you use a pointer (&) you will have one array with 2 names. This method is a shallow array clone in PHP.

Let’s see how to make a shallow copy of an array in PHP.

$cars=array('fer'=>'Ferrari','ben'=>'Benz','bmw'=>'BMW'); $cars2=&$cars; var_dump($cars2);
array (size=3) 'fer' => string 'Ferrari' (length=7) 'ben' => string 'Benz' (length=4) 'bmw' => string 'BMW' (length=3)

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. If you change a value in the array, the other array value will be changed.

$cars=array('fer'=>'Ferrari','ben'=>'Benz','bmw'=>'BMW'); $cars2=&$cars; $cars['vol']='Volvo'; var_dump($cars2);
array (size=4) 'fer' => string 'Ferrari' (length=7) 'ben' => string 'Benz' (length=4) 'bmw' => string 'BMW' (length=3) 'vol' => string 'Volvo' (length=5)

All you 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.

3. By ArrayObject class

Another way to clone or copy the array is by using the PHP ArrayObject class. The getArrayCopy() function of the ArrayObject class in PHP is used to create a copy of this ArrayObject. This function returns the copy of the array present in this ArrayObject.

$cars = new ArrayObject(['fer' => 'Ferrari', 'ben' => 'Benz', 'bmw' => 'BMW']); $cars2 = $cars->getArrayCopy(); var_dump($cars2);
array (size=3) 'fer' => string 'Ferrari' (length=7) 'ben' => string 'Benz' (length=4) 'bmw' => string 'BMW' (length=3)

4. With serialize and unserialize

PHP Serialize and Unserialize are functions used to convert a PHP value to a string or vice versa. Serialize is used to take a PHP value and convert it into a string that can be stored in a database or sent over a network. Unserialize is used to take a string and convert it back into a PHP value.

Serialize is often used to store objects in a database. It takes an object and converts it into a string, which can then be stored in a database. Unserialize is used to take the string and convert it back into an object. This is useful for retrieving objects from a database.

Serialize and Unserialize can also be used to store complex data structures in a database. For example, an array can be serialized and stored in a database. When the data is needed, it can be unserialized and the data structure can be used in the application.

$cars = array('fer' => 'Ferrari', 'ben' => 'Benz', 'bmw' => 'BMW'); $cars2 = unserialize(serialize($cars)); var_dump($cars2);
array (size=3) 'fer' => string 'Ferrari' (length=7) 'ben' => string 'Benz' (length=4) 'bmw' => string 'BMW' (length=3)

5. Copy array with array_replace() function

The PHP function array_replace() replaces an array’s values with those from another array or value. The array to be changed, the array containing the replacement values, and an optional third array that will be used to replace additional values are the three parameters it requires.

The array whose values will be changed is the array that has to be replaced. The array that holds the values to replace the original values is known as the array containing replacement values. The third array, which is optional, is used to replace any extra values that the initial array might not have contained.

All of the values in the first array will be replaced by the values in the second array using the array replace() function. The remaining values in the first array will remain intact if the second array has fewer items than the first array.

$cars = array('fer' => 'Ferrari', 'ben' => 'Benz', 'bmw' => 'BMW'); $cars2 = array_replace([],$cars); var_dump($cars2);
array (size=3) 'fer' => string 'Ferrari' (length=7) 'ben' => string 'Benz' (length=4) 'bmw' => string 'BMW' (length=3)

To copy or clone with this function in PHP, you have to pass an empty array as the first parameter. Then this function replaces the second array elements with the first array.

6. Clone with array_merge() function

The PHP array_merge() method is an effective tool for merging two or more arrays into a single array.
When you need to aggregate data from various sources into a single array, this function is extremely helpful.

When given two or more arrays as inputs, the array merge() function merges them into a single array.
Every element from the first array is taken by the function and added to the end of the second array.
If the same element appears in both arrays, the second array’s element will replace the first array’s element.

This function works exactly like the array_replace() function.

$cars = array('fer' => 'Ferrari', 'ben' => 'Benz', 'bmw' => 'BMW'); $cars2 = array_merge([],$cars); var_dump($cars2);
array (size=3) 'fer' => string 'Ferrari' (length=7) 'ben' => string 'Benz' (length=4) 'bmw' => string 'BMW' (length=3)

To copy or clone with this function in PHP, you have to pass an empty array as the first parameter. Then this function adds second array elements to the first array’s ends. It means copying the second array to an empty array.

7. How to copy the multidimensional array in PHP with user-defined function (an array and subarray)

A multidimensional array takes complexity to the next level. It is challenging in way that it can include many levels of subarrays and varying data types. Here’s the most robust function to deep-clone an array and subarray in PHP.

function clone_array($arr) < $clone = []; foreach ($arr as $k =>$v) < if (is_array($v)) < $clone[$k] = clone_array($v); >elseif (is_object($v)) < $clone[$k] = clone $v; >else < $clone[$k] = $v; >> return $clone; > $cars = ['fer' => 'Ferrari', 'ben' => 'Benz', 'bmw' => 'BMW']; $cars2 = clone_array($cars); var_dump($cars2);
array (size=3) 'fer' => string 'Ferrari' (length=7) 'ben' => string 'Benz' (length=4) 'bmw' => string 'BMW' (length=3)

8- How to copy or clone an array with PHP array_map() function

The array_map() function is a built-in PHP function to iterate an array. With this function, we can iterate the array and copy the elements to another array but to iterate we have to use a recursive function.

$cars = ['fer' => 'Ferrari', 'ben' => 'Benz', 'bmw' => 'BMW']; function array_clone($array) < return array_map(function($element) < return ((is_array($element)) ? array_clone($element) : ((is_object($element)) ? clone $element : $element ) ); >, $array); > $cars2 = array_clone($cars); var_dump($cars2);
array (size=3) 'fer' => string 'Ferrari' (length=7) 'ben' => string 'Benz' (length=4) 'bmw' => string 'BMW' (length=3)

In this example we use the recursive user define array_clone() function to copy the array to another array by the array_map() function.

Источник

How to copy a file from one directory to another using PHP

  • All categories
  • ChatGPT (11)
  • Apache Kafka (84)
  • Apache Spark (596)
  • Azure (145)
  • Big Data Hadoop (1,907)
  • Blockchain (1,673)
  • C# (141)
  • C++ (271)
  • Career Counselling (1,060)
  • Cloud Computing (3,469)
  • Cyber Security & Ethical Hacking (162)
  • Data Analytics (1,266)
  • Database (855)
  • Data Science (76)
  • DevOps & Agile (3,608)
  • Digital Marketing (111)
  • Events & Trending Topics (28)
  • IoT (Internet of Things) (387)
  • Java (1,247)
  • Kotlin (8)
  • Linux Administration (389)
  • Machine Learning (337)
  • MicroStrategy (6)
  • PMP (423)
  • Power BI (516)
  • Python (3,193)
  • RPA (650)
  • SalesForce (92)
  • Selenium (1,569)
  • Software Testing (56)
  • Tableau (608)
  • Talend (73)
  • TypeSript (124)
  • Web Development (3,002)
  • Ask us Anything! (66)
  • Others (2,231)
  • Mobile Development (395)
  • UI UX Design (24)

Join the world’s most active Tech Community!

Welcome back to the World’s most active Tech Community!

Subscribe to our Newsletter, and get personalized recommendations.

GoogleSign up with Google facebookSignup with Facebook

Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP

  • DevOps Certification Training
  • AWS Architect Certification Training
  • Big Data Hadoop Certification Training
  • Tableau Training & Certification
  • Python Certification Training for Data Science
  • Selenium Certification Training
  • PMP® Certification Exam Training
  • Robotic Process Automation Training using UiPath
  • Apache Spark and Scala Certification Training
  • Microsoft Power BI Training
  • Online Java Course and Training
  • Python Certification Course
  • Data Scientist Masters Program
  • DevOps Engineer Masters Program
  • Cloud Architect Masters Program
  • Big Data Architect Masters Program
  • Machine Learning Engineer Masters Program
  • Full Stack Web Developer Masters Program
  • Business Intelligence Masters Program
  • Data Analyst Masters Program
  • Test Automation Engineer Masters Program
  • Post-Graduate Program in Artificial Intelligence & Machine Learning
  • Post-Graduate Program in Big Data Engineering

COMPANY

WORK WITH US

DOWNLOAD APP

appleplaystore googleplaystore

CATEGORIES

CATEGORIES

  • Cloud Computing
  • DevOps
  • Big Data
  • Data Science
  • BI and Visualization
  • Programming & Frameworks
  • Software Testing © 2023 Brain4ce Education Solutions Pvt. Ltd. All rights Reserved. Terms & ConditionsLegal & Privacy

Источник

How do you copy a file in PHP without overwriting an existing file?

When you use the PHP copy function, the operation blindly copies over the destination file, even if it already exists. How do you copy a file safely, only performing the copy if there is no existing file?

4 Answers 4

The obvious solution would be to call file_exists to check to see if the file exists, but doing that could cause a race condition. There is always the possibility that the other file will be created in between when you call file_exists and when you call copy. The only safe way to check if the file exists is to use fopen.

When you call fopen, set the mode to ‘x’. This tells fopen to create the file, but only if it doesn’t exist. If it exists, fopen will fail, and you’ll know that you couldn’t create the file. If it succeeds, you will have a created a file at the destination that you can safely copy over. Sample code is below:

// The PHP copy function blindly copies over existing files. We don't wish // this to happen, so we have to perform the copy a bit differently. The // only safe way to ensure we don't overwrite an existing file is to call // fopen in create-only mode (mode 'x'). If it succeeds, the file did not // exist before, and we've successfully created it, meaning we own the // file. After that, we can safely copy over our own file. $filename = 'sourcefile.txt' $copyname = 'sourcefile_copy.txt' if ($file = @fopen($copyname, 'x')) < // We've successfully created a file, so it's ours. We'll close // our handle. if (!@fclose($file)) < // There was some problem with our file handle. return false; >// Now we copy over the file we created. if (!@copy($filename, $copyname)) < // The copy failed, even though we own the file, so we'll clean // up by itrying to remove the file and report failure. unlink($copyname); return false; >return true; > 

Источник

Оцените статью