Computer >> Computer tutorials >  >> Programming >> PHP

PHP program to delete an element from the array using the unset function


To delete an element from the array using the unset function, the PHP code is as follows −

Example

<?php
   $my_array = array("Joe", "Ben", "Mary", "Barun", "Sona", "Mona");
   unset($my_array[4]);
   print_r("After deleting the element, the array is");
   print_r ($my_array);
?>

Output

After deleting the element, the array isArray (
   [0] => Joe [1] => Ben [2] => Mary [3] => Barun [5] =>
   Mona
)

Above, an array is defined, with multiple strings −

$my_array = array("Joe", "Ben", "Mary", "Barun", "Sona", "Mona");

The unset function is used, by specifying the index of the element in the array that needs to be deleted. After the element is deleted, the output/array is printed on the screen −

unset($my_array[4]);
print_r("After deleting the element, the array is");
print_r ($my_array);