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

PHPServer Side ProgrammingProgramming

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

Example

 Live Demo

<?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);
raja
Published on 17-Aug-2020 15:31:32
Advertisements