19

How can I remove an element from an array?

For example:

$data = Array('first' , 'second' , 'third');
array_delete($data[2]);

#$data would now read Array('first', 'second')

Does such a built-in function exist? Thanks.

ensnare
  • 37,180
  • 60
  • 149
  • 218
  • 1
    possible duplicate of [How to delete an array element based on key](http://stackoverflow.com/questions/1672156/how-to-delete-an-array-element-based-on-key) – Peter Bailey Jan 18 '11 at 18:00

3 Answers3

43

yes. i would have made it shorter, but need at least 30- charcters. so here you go:

unset($data[2]);
alfred
  • 970
  • 9
  • 13
5

The above answers work. But here is what i got from the site listed below. I think its cool.

//deletes a number on index $idx in array and returns the new array  
function array_delete($idx,$array) {  
    unset($array[$idx]);  
    return (is_array($array)) ? array_values($array) : null;  
}

http://dev.kafol.net/2009/02/php-array-delete.html

Angel.King.47
  • 7,704
  • 14
  • 59
  • 84
  • 1
    yeah, returning the record deleted is nice... much like splice in javascript (there's an extra param which says how many items to delete) – alfred May 12 '11 at 07:51
4
unset($data[2]);

yes it does. unset().

dqhendricks
  • 17,761
  • 10
  • 48
  • 82