In PHP, how do I copy arrays for beginners?

In PHP, copying arrays can be done in several ways, depending on the requirements of your application. Here, we will cover the most common methods for beginners to understand.

Learn how to effectively copy arrays in PHP using various methods like assignment, array_slice, and array_merge.

PHP, array copy, PHP arrays, programming, web development


 1 [1] => 2 [2] => 3 )
print_r($array2); // Outputs: Array ( [0] => 100 [1] => 2 [2] => 3 )

// Method 2: Using array_slice
$array3 = array(4, 5, 6);
$array4 = array_slice($array3, 0); // Copy using array_slice
$array4[0] = 200; // Modifying $array4 won't affect $array3
print_r($array3); // Outputs: Array ( [0] => 4 [1] => 5 [2] => 6 )
print_r($array4); // Outputs: Array ( [0] => 200 [1] => 5 [2] => 6 )

// Method 3: Using array_merge
$array5 = array(7, 8, 9);
$array6 = array_merge(array(), $array5); // Copy using array_merge
$array6[0] = 300; // Modifying $array6 won't affect $array5
print_r($array5); // Outputs: Array ( [0] => 7 [1] => 8 [2] => 9 )
print_r($array6); // Outputs: Array ( [0] => 300 [1] => 8 [2] => 9 )
?>
    

PHP array copy PHP arrays programming web development