Deleting an element from an array in PHP

Posted by LaravelIndia - 1 year ago

\unset() method Note that when you use \unset() the array keys won't change/reindex. If you want to reindex the keys you can use \array_values() after \unset() which will convert all keys to numerical enumerated keys starting from 0.

Code

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

?> Output

[
    [0] => a
    [2] => c
]

\array_splice() method

Code

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

?> Output

[
    [0] => a
    [1] => c
]