There are many ways to delete elements from an array in PHP. Several common methods are listed below.

Delete one element from an array

If you want to delete an element from an array, you can use unset() orarray_splice()method.

If you know the value of the array element but not the key, you can usearray_search()to obtain the key.

unset() method

Note that if you use the unset() method, it will not change other keys. If you want to reorder and sort other keys, you can usearray_values()。

<?php
$array = array(0 => "a", 1 => "b", 2 => "c");
unset($array[1]);
           //↑ 你要删除的数组元素值的键
print_r($array);
?>

Output result:

Array (
    [0] => a
    [2] => c
)

array_splice() method

If you usearray_splice()method, the array keys will be automatically re-indexed, but it does not work on associative arrays. You need to usearray_values()to convert the keys to numeric keys.

<?php
$array = array(0 => "a", 1 => "b", 2 => "c");
array_splice($array, 1, 1);
                   //↑ Offset which you want to delete
print_r($array);
?>

Output result:

Array
(
    [0] => a
    [1] => c
)

array_splice()It has the same effect as the unset() function in releasing a specified element of an array.

Delete multiple elements from an array

If you want to delete multiple elements from an array, you cannot use unset() orarray_splice()function. You need to usearray_diff()orarray_diff_key()method. To use this method, you need to know the key or value to be deleted.

array_diff() method

If you know the array elements to delete, you can use array_diff().

<?php
$array = array(0 => "a", 1 => "b", 2 => "c");
$array = array_diff($array, ["a", "c"]);
                          //└────────┘→你要删除的元素
print_r($array );
?>

The output result is:

Array
(
    [1] => b
)

array_diff_key() method

If you know the key of the array element to delete, you can use array_diff_key(). You need to enter the key to delete in the key-value position of the second parameter of the function; the value is not required and can be anything.

<?php
$array = array(0 => "a", 1 => "b", 2 => "c");
$array = array_diff_key($array, [0 => "xy", "2" => "xy"]);
                               //↑           ↑ 你要删除的数组键
print_r($array);
?>

The output result is:

Array (
    [1] => b
)