PHP Program to delete element form the array

How to delete the elements of the array using PHP?

In this program, we are going to insert an element at a specified index. For that, we are first assigning value into the array arr[]. And to delete the element we are using the built-in function array_splice(). In the function we specify the array arr and position of the element to be deleted and the number of elements to be deleted. And at last print the elements in the array arr[] using foreach loop.

Syntax of array_splice() function


array_splice(array, start, length, array)

ALGORITHM

Step 1: Initialize an array arr[] with values

Step 2: Print the element currently in the array arr[] using foreach loop

Step 5: To delete the element from the array call the built-in function with parameters array_splice() with argument array arr and position of the element to be deleted and the number of elements to be deleted.

Step 6: Print the elements in the array arr[] using foreach loop

PHP Source Code

                                          <?php
$arr = array(1, 2, 3, 4, 5, 6, 7, 8, 9);
echo "Array before removing element: \n";
foreach ($arr as $x) {
    echo "$x ";
}
array_splice($arr, 3, 1);
echo "\nArray after removing element: \n";
foreach ($arr as $x) {
    echo "$x ";
}
?>
                                      

OUTPUT

Array before removing element:
1 2 3 4 5 6 7 8 9
Array after removing element:
1 2 3 5 6 7 8 9