PHP Program to copy all elements of an array into another array

What is an Array?

The array is one of the compound data types in PHP. The array can store similar multiple values in a single variable. Each element of the array has unique indexing starting from 0. There are three types of arrays in PHP Numeric array, Associative array, and Multidimensional array.

How copy all elements of an array into another array using PHP?

To copy all elements of an array into another array we first assign the values into the first array a1[] and create an empty array a2[]. After that, we find the size of the array a1[]  and assign it to the variable size. Then we have to perform for loop to copy the elements from a1[] to a2[] for this we assign value 0 to the variable i in for loop and perform the operation 'a2[i] = a1[i]' and the loop will iterate till the condition 'i < size'  becomes false and in every iteration, we increment the value of i by 1. After the completion of the for loop we can print the value of array a1[] and a2[] by using the for loop itself.


Step 1: Initialize an array a1[] with values

Step 2: Create another array a2[]

Step 3: Assign the size of the array a1[] into variable size by using the built-in function count()

Step 4: Assign the value 0 into the variable i and perform the sub-step until the condition 'i < size' and increment the value of variable i in every iteration

        (i) Assign the value of array a1[i] into the array a2[i]

Step 5: Print the elements of the array a1[] and a2[] using for loop

PHP Source Code

$a1 = array(58, 6, 71, 9, 10);
$a2 = array();
$size = count($a1);
for ($i = 0; $i < $size; $i++) {
    $a2[$i] = $a1[$i];
echo "Elements of first array: \n";
for ($i = 0; $i < $size; $i++) {
    echo "$a1[$i] ";
echo "\nElements of second array: \n";
for ($i = 0; $i < $size; $i++) {
    echo "$a2[$i] ";


Elements of first array:
58 6 71 9 10
Elements of second array:
58 6 71 9 10