Deleting An Element From An Array in PHP

Deleting elements from an array is easy as long as you know which index you or offset value you will be deleting. To delete an element, simply call unset() and pass in the array along with its index or offset.

<?php
// deleting by offset
$arr = [];
$arr[] = 'element0';
$arr[] = 'element1';
$arr[] = 'element2';

// delete 'element0' from the array
unset($arr[0]);

// deleting by index
$arr = [];
$arr['index0'] = 'element0';
$arr['index1'] = 'element1';
$arr['index2'] = 'element2';

// delete 'element1' from array
unset($arr['index1']);

Leave a comment

Leave a Reply