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]); 
    1
    • 1
      Nice speed of posting, do you training? :)
      – MDI
      CommentedJan 18, 2011 at 19:35
    4
    unset($data[2]); 

    yes it does. unset().

      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
      • 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
        CommentedMay 12, 2011 at 7:51

      Start asking to get answers

      Find the answer to your question by asking.

      Ask question

      Explore related questions

      See similar questions with these tags.