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.

0

3 Answers 3

45

Use the unset method:

unset($data[2]);
Sign up to request clarification or add additional context in comments.

1 Comment

Nice speed of posting, do you training? :)
4
unset($data[2]);

yes it does. unset().

Comments

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

1 Comment

yeah, returning the record deleted is nice... much like splice in javascript (there's an extra param which says how many items to delete)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.