php delete from array – Deleting an element from an array in PHP

php delete from array use the unset() function. there are 5 PHP functions used to remove specific element from an array. We can remove an element from an array by using unset command.

php delete from array – How to Delete an Element from an Array in PHP?

The unset() function is used to remove element from the array. The easiest way to remove or delete a single element from an array in PHP is to use the unset() function.

using unset()

$group_list = [0 => "a", 1 => "b", 2 => "c"];
unset($group_list[1]);

using \array_splice() method

$group_list = [0 => "a", 1 => "b", 2 => "c"];
\array_splice($group_list, 1, 1);

Deleting multiple array elements

using \array_diff() method

$group_list = [0 => "a", 1 => "b", 2 => "c", 3 => "c"];
$group_list = \array_diff($group_list, ["a", "c"]);
                          // └────────┘

using \array_diff_key() method

$group_list = [0 => "a", 1 => "b", 2 => "c"];
$group_list = \array_diff_key($group_list, [0 => "xy", "2" => "xy"]);

How to Delete an Element from an Array in PHP?

<?php
$group_list = array("a" => "Kohali", "b" => "Sachin", "c" => "Cartik");
unset($group_list["b"]); 
// RESULT: array("a" => "Kohali", "c" => "Cartik")
 
$group_list = array(1, 2, 3);
unset($group_list[1]);
// RESULT: array(0 => 1, 2 => 3)
?>

Using PHP array_splice() Function

<?php
$group_list=array("a"=>"ravindra","b"=>"munaf","c"=>"yuvraj","d"=>"dilyani");
$group_list2=array("a"=>"rohit","b"=>"bhuvneswer");
array_splice($group_list,0,2,$group_list2);
print_r($group_list);
?>

How To Remove Specific Array Element in PHP?

<?php
  $group_list = array("a" => "Kohali", "b" => "Sachin", "c" => "Cartik");
  unset($group_list["b"]);
?>

Another Example:

<?php
  $group_list = array(1, 2, 3, 4, 5);
  unset($group_list[3]);
  print_r($group_list)
?>

Don’t Miss : PHP Remove specific value from array

Read Also:  Add Edit And Delete Records Using jQuery Ajax PHP And MySQL

How to delete array in PHP?

use the unset() function

<?php
$group_list[0] = 'Kohali';
$group_list[1] = 'Rahul';

// just to delete an array:
unset ($group_list[0]);
// to delete all:
unset ($group_list);
?>