To remove an element from an array in PHP, you can use the unset()
function or the array_splice()
function.
unset()
function:$myArray = array('element1', 'element2', 'element3', 'element4');
// Remove an element by its index
unset($myArray[1]);
print_r($myArray);
Output:
Array
(
[0] => element1
[2] => element3
[3] => element4
)
array_splice()
function:$myArray = array('element1', 'element2', 'element3', 'element4');
// Remove an element by its index
array_splice($myArray, 1, 1);
print_r($myArray);
Output:
Array
(
[0] => element1
[1] => element3
[2] => element4
)
Both methods will remove the element at the specified index from the array. The unset()
function directly removes the element, while the array_splice()
function can be used to remove multiple elements from an array simultaneously.