Free Trial

Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.


  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • PrintPrint
Share this Page URL
Help

4. Arrays > 4.5. Deleting Elements from an Array

4.5. Deleting Elements from an Array

Problem

You want to remove one or more elements from an array.

Solution

To delete one element, use unset():

unset($array[3]);
unset($array['foo']);

To delete multiple noncontiguous elements, also use unset():

unset($array[3], $array[5]);
unset($array['foo'], $array['bar']);

To delete multiple contiguous elements, use array_splice():

array_splice($array, $offset, $length);

Discussion

Using these functions removes all references to these elements from PHP. If you want to keep a key in the array, but with an empty value, assign the empty string to the element:

$array[3] = $array['foo'] = '';

Besides syntax, there’s a logical difference between using unset() and assigning '' to the element. The first says, “This doesn’t exist anymore,” while the second says, “This still exists, but its value is the empty string.”


  

You are currently reading a PREVIEW of this book.

                                                                                                                    

Get instant access to over $1 million worth of books and videos.

  

Start a Free Trial


  
  • Safari Books Online
  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • PrintPrint