• Home
  • Deleting an element from an array in PHP

Deleting an element from an array in PHP

There are several ways to delete an element from an array in PHP:

  1. Use the unset() function: The unset() function removes a specific element from an array by its key. It takes the array and the key of the element to be removed as arguments, and returns null.
$array = array("apple", "banana", "orange");
unset($array[1]);

After the unset() function is called, the $array will be equal to array("apple", "orange").

  1. Use the array_splice() function: The array_splice() function removes a specified number of elements from an array, starting at a specified index. It takes the array, the index of the first element to be removed, and the number of elements to be removed as arguments, and returns an array containing the removed elements.
$array = array("apple", "banana", "orange");
$removed = array_splice($array, 1, 1);

After the array_splice() function is called, the $array will be equal to array("apple", "orange") and the $removed variable will be equal to array("banana").

  1. Use the array_slice() function: The array_slice() function removes a specified range of elements from an array and returns the remaining elements as a new array. It takes the array, the index of the first element to be removed, and the index of the last element to be removed as arguments.
$array = array("apple", "banana", "orange");
$sliced = array_slice($array, 0, 1);

After the array_slice() function is called, the $array will be unchanged, and the $sliced variable will be equal to array("apple").

  1. Reassign the array: You can also remove an element from an array by reassigning the array with a new set of elements that do not include the element to be removed.
$array = array("apple", "banana", "orange");
$array = array_diff($array, array("banana"));

Regardless of which method you use, it is important to note that deleting an element from an array does not preserve the keys of the remaining elements. For example, if you delete the second element of an array with unset(), the third element will become the second element, but it will not have the key 1. If you need to preserve the keys of the remaining elements, you can use the array_values() function to reset the keys to a sequential numbering.

$array = array("apple", "banana", "orange");
unset($array[1]);
$array = array_values($array);