473,396 Members | 1,917 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,396 software developers and data experts.

Delete an array from array while in a foreach loop

dlite922
1,584 Expert 1GB
I can't believe I haven't come across this in all of my PHP programming (or my brain is currently locked)...I need to delete an array from an array that i'm traversing through with a foreach.

Read the comments:
Expand|Select|Wrap|Line Numbers
  1.  
  2. $test1 = array("one","two","three"); 
  3. $test2 = array("Four",true,"6"); 
  4. $test3 = array("Seven",8,0x09); 
  5.  
  6. // a non-keyed array. (in actuality its a mysql result set)
  7. $combined = array($test1,$test2,$test3); 
  8.  
  9. // Notice ampersand (foreach by reference)
  10. foreach ($combined as &$test)
  11. {
  12.     //I do some other processing here. 
  13.  
  14.     // then attemp to remove the second $test2 for example
  15.     if($test2[1] === true)    
  16.     {
  17.         // remove it!! 
  18.         // HOW?        
  19.  
  20.     }
  21. }
  22.  
  23. // this should print the arrays $test1 and $test3 but not $test2
  24. print_r($combined); 
  25.  
I think in the past I would have created a new array and pushed the values I wanted into that new one. Then I learned that I don't need to do that and use enough memory for ONE array and not mess with two copies.

Hooray, but now...how do I delete one of these values?


Thanks guys, I think I'm losing it today, so I apologize if this is a mere brain fart on my end.



Dan
Sep 16 '09 #1
5 9847
Markus
6,050 Expert 4TB
unset() it?
Sep 16 '09 #2
dlite922
1,584 Expert 1GB
array_remove()

ha! I feel silly.



Dan

EDIT: what? link doesn't exist! *GASP* Oops!

It's because RQuadling at GMail dot com wrote it. (see unset comment section)

Expand|Select|Wrap|Line Numbers
  1. <?php
  2. /**
  3.   * array array_remove ( array input, mixed search_value [, bool strict] )
  4.   **/
  5. function array_remove(array &$a_Input, $m_SearchValue, $b_Strict = False) {
  6.     $a_Keys = array_keys($a_Input, $m_SearchValue, $b_Strict);
  7.     foreach($a_Keys as $s_Key) {
  8.         unset($a_Input[$s_Key]);
  9.     }
  10.     return $a_Input;
  11. }
  12. ?>
  13.  
Sep 16 '09 #3
dlite922
1,584 Expert 1GB
@Markus
it is a very vague word in computer science unless I see where your finger is pointing.

If your referring to $test, then no that doesn't work. Even if you pass it by reference, it will just delete the reference (pointer) variable, not the actual var.

Try this:
Make a wrapper function for unset() and see if you can use it to erase variables.
I'll bet you my lunch money that it won't work. :)

hehehe
:P



Dan
Sep 16 '09 #4
dlite922
1,584 Expert 1GB
Working code using RQuadling's function:

Expand|Select|Wrap|Line Numbers
  1.  
  2. function array_remove(array &$a_Input, $m_SearchValue, $b_Strict = False) {
  3.     $a_Keys = array_keys($a_Input, $m_SearchValue, $b_Strict);
  4.     foreach($a_Keys as $s_Key) {
  5.         unset($a_Input[$s_Key]);
  6.     }
  7.     return $a_Input;
  8. }
  9.  
  10.  
  11. $test1 = array("one","two","three"); 
  12. $test2 = array("Four",true,"6"); 
  13. $test3 = array("Seven",8,0x09); 
  14.  
  15. // a non-keyed array. (in actuallity its a mysql result set)
  16. $combined = array($test1,$test2,$test3); 
  17.  
  18. // Notice ampersand (foreach by reference)
  19. foreach ($combined as &$test)
  20. {
  21.     //I do some other processing here. 
  22.  
  23.     // then attemp to remove the second $test2 for example
  24.     if($test2[1] === true)    
  25.     {
  26.         array_remove($combined,$test2); 
  27.     }
  28. }
  29.  
  30. // this should print the arrays $test1 and $test3 but not $test2
  31. print_r($combined); 
  32.  
  33.  
OUTPUT:
Expand|Select|Wrap|Line Numbers
  1. Array
  2. (
  3.     [0] => Array
  4.         (
  5.             [0] => one
  6.             [1] => two
  7.             [2] => three
  8.         )
  9.  
  10.     [2] => Array
  11.         (
  12.             [0] => Seven
  13.             [1] => 8
  14.             [2] => 9
  15.         )
  16.  
  17. )
  18.  
  19.  
  20.  
If anybody thinks of another way without another traversal loop, let me know please.


Dan
Sep 16 '09 #5
Atli
5,058 Expert 4TB
Expand|Select|Wrap|Line Numbers
  1. <?php
  2. $test1 = array("one","two","three"); 
  3. $test2 = array("Four",true,"6"); 
  4. $test3 = array("Seven",8,0x09); 
  5.  
  6. $combined = array($test1,$test2,$test3); 
  7.  
  8. foreach ($combined as $key => &$test)
  9. {
  10.     // Note how I use $test, rather then $test2 as you did.
  11.     // (which didn't really make sense, btw)
  12.     if($test[1] === true)    
  13.     {
  14.         unset($combined[$key]);
  15.     }
  16. }
  17.  
  18. print_r($combined); 
  19. ?>
Expand|Select|Wrap|Line Numbers
  1. Array
  2. (
  3.     [0] => Array
  4.         (
  5.             [0] => one
  6.             [1] => two
  7.             [2] => three
  8.         )
  9.  
  10.     [2] => Array
  11.         (
  12.             [0] => Seven
  13.             [1] => 8
  14.             [2] => 9
  15.         )
  16.  
  17. )
How 'bout that?
Sep 17 '09 #6

Sign in to post your reply or Sign up for a free account.

Similar topics

8
by: cody | last post by:
currently, foreach takes a IEnumerable as parameter, so we can do: foreach (int i in array){} what about an additional form of foreach that takes an IEnumerator as parameter, so we can do: ...
18
by: Ken Varn | last post by:
Is there any way to reset a foreach loop to re-iterate through the collection as if it were starting from the beginning? Namely, if I delete an item out of a collection, I want to be able to reset...
2
by: chris | last post by:
Hi there, I created a Multidimensional array of labels Label lblMultiArray = new Label { {Label3, LblThuTotal}, {Label4,LblFriTotal} }; Now I would like to compare the values in the array,...
2
by: ad | last post by:
I want to delete a DataRowView in a DataView if the DataRowView not checked OK. (CheckRow is a function for checking ) I used the codes below: But when some row is delete, it fail , the error...
4
by: Jack E Leonard | last post by:
I'm looping through the keys and values of a form submission using foreach($_POST as $key => $value) echo "$key = $value<br>"; No problems there. All works as expected. But seveal of the...
29
by: Jon Slaughter | last post by:
Is it safe to remove elements from an array that foreach is working on? (normally this is not the case but not sure in php) If so is there an efficient way to handle it? (I could add the indexes to...
1
by: Perl Beginner | last post by:
I hope i can articulate this question properly. i have been trying to figure this out for over a week. I am comparing the contents of two files, but the comparison is done inside of a foreach...
3
by: SM | last post by:
Hello, I have an array that holds images path of cd covers. The array looks like this: $cd = array( 589=>'sylver.jpg', 782=>'bigone.jpg', 158=>'dime.jpg' );
2
by: gomako | last post by:
Hi, I'm new, so please let me know if any of my forum etiquette is wrong! Apologies for the fairly nondescript subject line, but I am being driven insane by it. Anyhow, I have a form with...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.