Jump to content

[SOLVED] Unsetting a value in an array without "unset()"


vnums

Recommended Posts

Hi,

 

I have a question that I could really use an answer to and thus far have not been able to find one.  Let's say I have an array:

Array
(
[0] => a
[1] => b
[2] => c
)

I want to remove "[1] => b" from it. 

 

"unset($Array[1]); " yeilds:

 

Array
(
[0] => a
[2] => c
)

 

Needless to say, if I want to iterate across this array again, it is going to stumble on an undefined index if I do it in a for loop (for($i=0; $i<count($array); $i++)), eventually, $i will get to 1, at which time happy error time happens.  So, I am looking for some magical function that will do something like:

 

magic_function($array[1]) which will yeild:

Array
(
[0] => a
[1] => c
)

 

Does this function exist? If not, is there any easy way to do this? I'm sure splitting/splicing the array at the points around where you want to remove the element and then re-combining them might work, but I am going to be taking a lot of things out of the array and re-iterating over it and that's just too much overhead. 

 

Thanks in advance for any help, much appreciated!

 

If you must do it this way you can do something like...

 

$array = array('a', 'b', 'c');

unset($array[1]);
$array = array_reverse(array_reverse($array));

 

It will take b out and if you print $array it it will print

Array
(
[0] => a
[1] => c
)

@PFM: Thanks, for some reason the thought of using a foreach didnt cross my mind, even though I have been using them everywhere else.  Problem is I need to keep track of an index that I cant do with a for-each loop if they arent in a perfect 1,2,3,4,5 progression.  For instance if each time it goes through the foreach it increments a counter by 1 for instance, that's not going to be the index of the array if the array doesnt have a a[2] value for instance.  Though I'm sure there's a way around that too.

 

@Nhoj: This is actually a clever solution and works for me.  Much appreciated!

 

Thank you both!

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.