21

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
  • 40,069
  • 64
  • 158
  • 224

3 Answers3

45

Yes, I would have made it shorter, but it needs at least 30 characters. so here you go:

unset($data[2]);
8ctopus
  • 2,617
  • 2
  • 18
  • 25
alfred
  • 1,000
  • 9
  • 13
4
unset($data[2]);

yes it does. unset().

dqhendricks
  • 19,030
  • 11
  • 50
  • 83
4

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,922
  • 14
  • 60
  • 85
  • 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