Easy Tutorial
❮ Verilog2 Reset Android Tutorial Fragment Base ❯

PHP Remove Elements from Array

Category Programming Techniques

There are several ways to remove elements from an array in PHP. Here are a few commonly used methods.

Removing a Single Element from the Array

If you want to remove a single element from the array, you can use the unset() or array_splice() method.

If you know the value of the array element but not the key, you can use array_search() to get the key.

unset() Method

Note that if you use the unset() method, it will not change other keys. If you want to reindex other keys, you can use array_values().

<?php
$array = array(0 => "a", 1 => "b", 2 => "c");
unset($array[1]);
           //↑ Key of the array element you want to delete
print_r($array);
?>

Output:

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

array_splice() Method

If you use the array_splice() method, the array keys will be automatically reindexed, but this does not work for associative arrays. You need to use array_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:

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

array_splice() works similarly to unset() in removing specified elements from the array.

Removing Multiple Elements from the Array

If you want to remove multiple elements from the array, you cannot use unset() or array_splice(). Instead, you need to use array_diff() or array_diff_key(), which require knowing the keys or values of the elements to be deleted.

array_diff() Method

If you know the elements to be deleted, you can use array_diff().

<?php
$array = array(0 => "a", 1 => "b", 2 => "c");
$array = array_diff($array, ["a", "c"]);
                          //└────────┘→Elements you want to delete
print_r($array);
?>

Output:

Array
(
    [1] => b
)

arraydiffkey() Method

If you know the keys of the elements to be deleted, you can use array_diff_key(). You need to input the keys to be deleted in the second parameter of the function, and the values can be arbitrary.

<?php
$array = array(0 => "a", 1 => "b", 2 => "c");
$array = array_diff_key($array, [0 => "xy", "2" => "xy"]);
                               //↑           ↑ Keys of the elements you want to delete
print_r($array);
?>

Output:

Array (
    [1] => b
)
❮ Verilog2 Reset Android Tutorial Fragment Base ❯