Question:
[PHP] Deleting an array entry?
William E
2008-03-21 07:16:51 UTC
I need to get rid of the bananas entry from:

array("1", "2", "bananas", "3", "4");

What PHP function do I use to do that.

As simple as possible please - there is absolutely no need to go into long explanations of your own functions.

If it helps, I know the index of the entries.
Three answers:
Björn Eberhardt
2008-03-21 07:32:34 UTC
$set = array("1", "2", "bananas", "3", "4");



the set will now have this structure

[0] => 1,

[1] => 2,

[2] => "bananas",

[3] => 3,

[4] => 4



As you don't know yet which entry has the value "bananas", you have to search for it.



Use $key = array_search($needle, $haystack); to discover which is the first key containing the needle, in this case "bananas".



To remove a value from the array, use unset($set[$key]);



combined into one command:



unset($set[array_search("bananas", $set)]);



The data structure now looks like this:

[0] => 1,

[1] => 2,

[3] => 3,

[4] => 4



Note that there is a gap between 1 and 3. Using e.g. sort($set); will now reorder the numbers in ascending order and at the same time delete the gap.
kainaw
2008-03-21 14:28:23 UTC
You need to know the index. You unset the variable. For example, your creation will number the indexes as 0=>'1', 1=>'2', 2=>'bananas', 3=>'3' and 4=>'4'. Assume you assigned this array to the name $myarray. You delete the index 2 (which contains bananas) with unset($myarray[2]).



Just so you know, setting $myarray[2]=null will not delete the entire index. It will keep index 2 and set it to null.



Also, this will not renumber the indexes 3 and 4. You now have an array that does not have an index 2. You can copy $myarray to $mynewarray value by value to cause it to reindex $mynewarray.
NoLife4Ever
2008-03-21 15:01:11 UTC
$list = array("1", "2", "bananas", "3", "4");

$list[2] = NULL;


This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.
Continue reading on narkive:
Loading...