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!

 

Link to comment
Share on other sites

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
)

Link to comment
Share on other sites

@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!

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.