PHP: remove element from a PHP array

You can easily remove any elements from a given array inside your PHP code using the function unset(); You just need the array name with index to remove it. I'm giving a small example, which will help to understand about removing any element from your PHP array.

## your initial PHP array
$array = array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
## output your array
print implode(' ,', $array) . "\n";
## Output : 1 ,2 ,3 ,4 ,5 ,6 ,7 ,8 ,9 ,10

## removing 2 values from array
unset($array[5]);
unset($array[7]);
print implode(' ,', $array) . "\n";
## Output : 1 ,2 ,3 ,4 ,5 ,7 ,9 ,10


The given example will declare an array of 10 elements from 1 to 10. It will print 10 elements using comma separation. After that it will remove 2 elements from the array, and print the elements again. And you'll find that 2 elements are missing after delete from first array set.

Comments

Anonymous said…
This does not always work with PHP5 as you cannot use unset() on some array types now. This can cause a lot of trouble for backwards compatibility with PHP4 so please beware.
Francis said…
I found there is a bug.
$arr = array(1, 2, 3, 4);
var_dump($arr);
// [0] => 1; [1] => 2; [2] => 3; [3] => 4;

unset($arr[2]);
var_dump($arr);
// [0] => 1; [1] => 2; [3] => 4;

the index will not change if an element has been removed.
I don't think this a really remove.
Unknown said…
Francis,

If the element is gone, it's removed.

That's not a bug.
floris said…
it is not REINDEXED

it is by
$myar = array_values($myar);
floris said…
it is not REINDEXED!

it is by
$myar = array_values($myar);
floris said…
it is not REINDEXED!

it is by
$myar = array_values($myar);
shaffy said…
Hey!i think this is complete bcoz m nt understand plz complete it.
alfasin said…
Francis, that's what unset does - it removes the item without re-indexing the array.

The effect you want can be achieved by using array_splice() which removes the item and re-indexes the array.
Anonymous said…

Great post! Yes, unset just leaves the indices as they were before, and does not rearrange them. There are some alternatives and workarounds as clearly explained here:

Delete an element from an array in PHP