Can You Copy an Array?

deepak singh
Posts: 686
Joined: Fri Sep 30, 2016 4:19 pm

Can You Copy an Array?

Postby deepak singh » Sat Oct 01, 2016 5:24 pm

Can You Copy an Array?

Posts: 1279
Joined: Sun Aug 28, 2016 10:45 am

Re: Can You Copy an Array?

Postby rameshkhd » Sat Oct 01, 2016 5:25 pm

You can create a new array by copying an existing array using the assignment statement. Note that the new array is not a reference to the old array. If you want a reference variable pointing to the old array, you can use the reference operator "&". Here is a PHP script on how to copy an array:
$oldArray = array("Zero"=>"PHP", "One"=>"Perl", "Two"=>"Java");
$newArray = $oldArray;
$refArray = &$oldArray;
$newArray["One"] = "Python";
$refArray["Two"] = "C#";
print("\$newArray[\"One\"] = ".$newArray["One"]."\n");
print("\$oldArray[\"One\"] = ".$oldArray["One"]."\n");
print("\$refArray[\"Two\"] = ".$refArray["Two"]."\n");
print("\$oldArray[\"Two\"] = ".$oldArray["Two"]."\n");
This script will print:
$newArray["One"] = Python
$oldArray["One"] = Perl
$refArray["Two"] = C#
$oldArray["Two"] = C#

Return to “PHP”

Who is online

Users browsing this forum: No registered users and 2 guests