Created 8 month back

How to delete an element from an array in PHP

Deleting just one array element

You can use unset() If you want to delete just one array element or alternatively \array_splice().

Code examples:

With unset() method:

$array = [0 => "a", 1 => "b", 2 => "c"];
unset($array[1]);
          // ↑ Key which you want to delete

With \array_splice() method:

$array = [0 => "a", 1 => "b", 2 => "c"];
\array_splice($array, 1, 1);
                   // ↑ Offset which you want to delete

Deleting multiple array elements

For deleting multiple array elements you can use \array_diff() method or \array_diff_key() method

With \array_diff() method:

$array = [0 => "a", 1 => "b", 2 => "c", 3 => "c"];
$array = \array_diff($array, ["a", "c"]);
                          // └────────┘
                          // Array values which you want to delete

With \array_diff_key() method:

$array = [0 => "a", 1 => "b", 2 => "c"];
$array = \array_diff_key($array, [0 => "xy", "2" => "xy"]);
                               // ↑           ↑
                               // Array keys which you want to delete