vnums Posted January 11, 2008 Share Posted January 11, 2008 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 https://forums.phpfreaks.com/topic/85478-solved-unsetting-a-value-in-an-array-without-unset/ Share on other sites More sharing options...
PFMaBiSmAd Posted January 11, 2008 Share Posted January 11, 2008 Don't use a for() loop with an incrementing index. Use a foreach() loop - http://www.php.net/foreach Link to comment https://forums.phpfreaks.com/topic/85478-solved-unsetting-a-value-in-an-array-without-unset/#findComment-436231 Share on other sites More sharing options...
Nhoj Posted January 11, 2008 Share Posted January 11, 2008 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 https://forums.phpfreaks.com/topic/85478-solved-unsetting-a-value-in-an-array-without-unset/#findComment-436262 Share on other sites More sharing options...
vnums Posted January 12, 2008 Author Share Posted January 12, 2008 @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 https://forums.phpfreaks.com/topic/85478-solved-unsetting-a-value-in-an-array-without-unset/#findComment-437128 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.