PHP Program to insert values into array

Insert values into an array

In this program, we are going to see how users can insert values into the array. For example, the user can specify the length of the array and also insert the elements into it. 

How to insert values into an array using PHP?

To insert values into an array first we have to read the limit of the array into the variable len. Then we have to initialize an empty array arr[] and after that, we have to assign the value 0 into the variable i and perform the loop until the condition 'i < len' becomes false and also increment the value of the variable i in every iteration and in the loop block we have to read the elements into the array a[i] from the user.

ALGORITHM

Step 1: Accept the limit of the array from the user and assign it to the variable len

Step 2: Initialize an empty array arr[]

Step 3: Assign the value 0 into the variable i and perform the sub-step until the condition 'i < len' becomes false and increment the value of variable i in every iteration

        (i) Assign the computed value of 'i + 1' into the variable j (only for printing the element count in sub-step ii)

        (ii) Read the elements from the user and assign them to the array arr[i]

Step 4: Print every element of the array arr[] using the for loop

PHP Source Code

                                          <?php
$len = readline("Enter the limit of the array: ");
$arr = array();
for ($i = 0; $i < $len; $i++) {
    $j = $i + 1;
    $arr[$i] = readline("Enter element $j: ");
}
echo "The elements in the array are: \n";
for ($i = 0; $i < $len; $i++) {
    echo "$arr[$i] ";
}
?>
                                      

OUTPUT

Enter the limit of the array: 5
Enter element 1: 1
Enter element 2: 2
Enter element 3: 3
Enter element 4: 4
Enter element 5: 5
The elements in the array are:
1 2 3 4 5