Open In App

How to delete an Element From an Array in PHP ?

There are multiple ways to delete an element from an array in PHP. This article discusses some of the most common methods used in PHP to delete an element from an array.

Functions used:



Steps used:

Example 1: This example uses unset() function to delete the element. The unset() function takes the array as a reference and does not return anything.






<?php
 
  // Declaring associated array
  $ass_arr = ["a"=>"Geeks", "b"=>"For", "c"=>"Geeks"];
 
  // Deleting element associated with key "b"
  unset($ass_arr["b"]);
 
  // Printing array after deleting the element
  print_r($ass_arr);
 
  // Declaring indexed array
  $ind_arr = ["Geeks","For","Geeks"];
 
  // Deleting element and index 1
  unset($ind_arr[1]);
 
  // Printing array after deleting the element
  print_r($ind_arr);
?>

Output
Array
(
    [a] => Geeks
     => Geeks
)
Array
(
    [0] => Geeks
    [2] => Geeks
)

From the output we can see that unset() has not changed the index for other elements in indexed array.

Example 2: This example uses array_splice() function to delete element from array.




<?php
 
  // Declaring associated array
  $ass_arr = ["a"=>"Geeks", "b"=>"For", "c"=>"Geeks"];
 
  // Deleting element associated with key "b"
  array_splice($ass_arr,1,1);
 
  // Printing array after deleting the element
  print_r($ass_arr);
 
  // Declaring indexed array
  $ind_arr = ["Geeks","For","Geeks"];
 
  // Deleting element and index 1
  array_splice($ind_arr,1,1);
 
  // Printing array after deleting the element
  print_r($ind_arr);
?>

Output
Array
(
    [a] => Geeks
     => Geeks
)
Array
(
    [0] => Geeks
    [1] => Geeks
)

Example 3: This example uses array_diff() function to delete the elements. Please note that the array values are passed as second parameter not the index. This function takes array parameter by value not reference and returns an array as output.




<?php
 
  // Declaring associated array
  $ass_arr = ["a"=>"Geeks", "b"=>"For", "c"=>"Geeks"];
 
  // Deleting element associated with key "b"
  $ass_arr = array_diff($ass_arr,["For"]);
 
  // Printing array after deleting the element
  print_r($ass_arr);
 
  // Declaring indexed array
  $ind_arr = ["Geeks","For","Geeks"];
 
  // Deleting element and index 1
  $ind_arr = array_diff($ind_arr,["For"]);
 
  // Printing array after deleting the element
  print_r($ind_arr);
?>

 
 

Output
Array
(
    [a] => Geeks
     => Geeks
)
Array
(
    [0] => Geeks
    [2] => Geeks
)

 


Article Tags :