-2

How can I delete all the elements from an array, except for one in particular?

laurent
  • 83,816
  • 72
  • 267
  • 404

1 Answers1

4

You can unset individual elements using the unset function:

unset($array['element']);

A quick way to do what you intend is to simply create a new array:

$new_array = array('element' => $old_array['element']);
unset($old_array);

Or use array_slice:

$new_array = array_slice($old_array, $offset, 1, true);
Sander Marechal
  • 22,658
  • 12
  • 62
  • 94
  • 1
    your code is more clear (or usable at least) as `$myarray = array('element' => $myarray['element']);` great anwser!!! – Luis Siquot Aug 02 '11 at 14:10