Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the best way to delete array item in PHP?

Tags:

arrays

php

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

like image 991
lovespring Avatar asked Nov 17 '09 10:11

lovespring


People also ask

Which method is used to delete an element from an array in PHP?

Answer: Use the PHP unset() Function If you want to delete an element from an array you can simply use the unset() function.

Can we delete an element from an array?

Java arrays do not provide a direct remove method to remove an element. In fact, we have already discussed that arrays in Java are static so the size of the arrays cannot change once they are instantiated. Thus we cannot delete an element and reduce the array size.


2 Answers

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().

like image 137
Stefan Gehrig Avatar answered Sep 26 '22 18:09

Stefan Gehrig


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

like image 42
Peter Lindqvist Avatar answered Sep 25 '22 18:09

Peter Lindqvist