tags:

views:

191

answers:

3

Could you tell me your way to delete an item from array, do u think it's good?

+5  A: 

The common way:

According to the manual

unset($arr[5]); // This removes the element from the array

The filtered way:

There is also the array_filter() function to take care of filtering arrays

$numeric_data = array_filter($data, "is_numeric");

To get a sequential index you can use

$numeric_data = array_values($numeric_data);

References
PHP – Delete selected items from an array

Peter Lindqvist
Peter, thank you.
lovespring
+2  A: 

It depends. If want to remove an element without causing gaps in the indexes, you need to use array_splice:

$a = array('a','b','c', 'd');
array_splice($a, 2, 1);
var_dump($a);

Output:

array(3) {
  [0]=>
  string(1) "a"
  [1]=>
  string(1) "b"
  [2]=>
  string(1) "d"
}

Using unset can work, but this results in a non-continuous index. This can sometimes be a problem when you iterate over the array using count($a) - 1 as a measure of the upper bound:

$a = array('a','b','c', 'd');
unset($a[2]);
var_dump($a);

Output:

array(3) {
  [0]=>
  string(1) "a"
  [1]=>
  string(1) "b"
  [3]=>
  string(1) "d"
}

As you see, count is now 3 but the index of the last element is also 3.

My recommendation is therefore to use array_splice for arrays with numerical indexes, and use unset only for arrays (dictionaries really) with non-numerical indexes.

John
alternatively you could call `unset($a[2]); $a = array_values($a);`
nickf
thank you, John.
lovespring
+2  A: 

That depends:

$a1 = array('a' => 1, 'b' => 2, 'c' => 3);
unset($a1['b']);
// array('a' => 1, 'c' => 3)

$a2 = array(1, 2, 3);
unset($a2[1]);
// array(0 => 1, 2 => 3)
// note the missing index 1

// solution 1 for numeric arrays
$a3 = array(1, 2, 3);
array_splice($a3, 1, 1);
// array(0 => 1, 1 => 3)
// index is now continous

// solution 2 for numeric arrays
$a4 = array(1, 2, 3);
unset($a4[1]);
$a4 = array_values($a4);
// array(0 => 1, 1 => 3)
// index is now continous

Generally unset() is safe for hashtables (string-indexed arrays), but if you have to rely on continous numeric indexes you'll have to use either array_splice() or a combination of unset() and array_values().

Stefan Gehrig
Why would you use unset combined with array_values rather than array_splice?
John
@John: One scenario I can think about is, when you want to remove several items from one array. With the `unset()`-way you can remove the values without having to think about changing keys - if you're done your run the array through `array_values()` to normalize the indexing. That's cleaner and faster than using `array_splice()` several times.
Stefan Gehrig