remove an element from the middle of an array in php

To remove an element from the middle of an array in PHP, you can use the array_splice() function. This function removes a portion of the array and replaces it with something else.

To remove a single element from the middle of the array, you can use the following code:

main.php
$array = array('a', 'b', 'c', 'd', 'e');
$index = 2; // index of the element to remove
array_splice($array, $index, 1);
print_r($array);
137 chars
5 lines

In this example, $array is the original array, and $index is the index of the element to remove (in this case, 2 corresponds to the third element, c). The array_splice() function removes one element starting from the $index and modifies the original array. Finally, we print the modified array using print_r().

The resulting array will be:

main.php
Array
(
    [0] => a
    [1] => b
    [2] => d
    [3] => e
)
62 chars
8 lines

Note that the elements after the removed element will shift to the left to fill the gap.

related categories

gistlibby LogSnag