tags:

views:

9693

answers:

4

Hi,

does anyone know an easy way to delete an element from a php array? I mean so that foreach($array) no longer includes that element. I thought that setting it to null would do it, but apparently not.

Thanks,

Ben

+12  A: 

You use unset:

<?php
$x = array(1, 2);
unset($x[0]);
var_dump($x);
?>
Konrad Rudolph
+4  A: 
unset($array[$index]);
Eran Galperin
+13  A: 

It should be noted that unset() will keep indexes untouched, which is what you'd expect when using string indexes (array as hashtable), but can be quite surprising when dealing with integer indexed arrays:

$array = array(0, 1, 2, 3);
unset($array[2]);
var_dump($array);
/* array(3) {
  [0]=>
  int(0)
  [1]=>
  int(1)
  [3]=>
  int(3)
} */

$array = array(0, 1, 2, 3);
array_splice($array, 2, 1);
var_dump($array);
/* array(3) {
  [0]=>
  int(0)
  [1]=>
  int(1)
  [2]=>
  int(3)
} */

So array_splice() can be used if you'd like to normalize your integer keys. Another option is using array_values() after unset():

$array = array(0, 1, 2, 3);

unset($array[2]);
$array = array_values($array);
var_dump($array);
/* array(3) {
  [0]=>
  int(0)
  [1]=>
  int(1)
  [2]=>
  int(3)
} */
Stefan Gehrig
+2  A: 

Also, for a named element:

unset($array["elementName"]);

CapsicumDreams