473,705 Members | 3,166 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

safe to delete elements of array in foreach

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 a temp array and
delete afterwards if necessary but since I'm actually working in a nested
situation this could get a little messy. I guess I could set there values to
null and remove them afterwards?

Thanks,
Jon
May 18 '07 #1
29 4241
On May 18, 11:05 am, "Jon Slaughter" <Jon_Slaugh...@ Hotmail.com>
wrote:
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 a temp array and
delete afterwards if necessary but since I'm actually working in a nested
situation this could get a little messy. I guess I could set there values to
null and remove them afterwards?

Thanks,
Jon
Why don't you try it and see what happens?

May 18 '07 #2

"ZeldorBlat " <ze********@gma il.comwrote in message
news:11******** *************@p 77g2000hsh.goog legroups.com...
On May 18, 11:05 am, "Jon Slaughter" <Jon_Slaugh...@ Hotmail.com>
wrote:
>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 a temp array and
delete afterwards if necessary but since I'm actually working in a nested
situation this could get a little messy. I guess I could set there values
to
null and remove them afterwards?

Thanks,
Jon

Why don't you try it and see what happens?
Um... cause I did... but that doesn't mean much. Just cause someone tries
something doesn't prove that it will always work like that...

got any more bright ideas?

Or is the question to hard for you?
May 18 '07 #3
On May 18, 11:40 am, "Jon Slaughter" <Jon_Slaugh...@ Hotmail.com>
wrote:
"ZeldorBlat " <zeldorb...@gma il.comwrote in message

news:11******** *************@p 77g2000hsh.goog legroups.com...
On May 18, 11:05 am, "Jon Slaughter" <Jon_Slaugh...@ Hotmail.com>
wrote:
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 a temp array and
delete afterwards if necessary but since I'm actually working in a nested
situation this could get a little messy. I guess I could set there values
to
null and remove them afterwards?
Thanks,
Jon
Why don't you try it and see what happens?

Um... cause I did... but that doesn't mean much. Just cause someone tries
something doesn't prove that it will always work like that...

got any more bright ideas?

Or is the question to hard for you?
No, the question is not to (sic) hard for me. But, as you've already
discovered, it isn't that difficult to test, either.

May 18 '07 #4
ZeldorBlat wrote:
On May 18, 11:40 am, "Jon Slaughter" <Jon_Slaugh...@ Hotmail.com>
wrote:
>"ZeldorBlat " <zeldorb...@gma il.comwrote in message

news:11******* **************@ p77g2000hsh.goo glegroups.com.. .
>>On May 18, 11:05 am, "Jon Slaughter" <Jon_Slaugh...@ Hotmail.com>
wrote:
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 a temp array and
delete afterwards if necessary but since I'm actually working in a nested
situation this could get a little messy. I guess I could set there values
to
null and remove them afterwards?
Thanks,
Jon
Why don't you try it and see what happens?
Um... cause I did... but that doesn't mean much. Just cause someone tries
something doesn't prove that it will always work like that...

got any more bright ideas?

Or is the question to hard for you?

No, the question is not to (sic) hard for me. But, as you've already
discovered, it isn't that difficult to test, either.
Sorry, I agree with Jon on this one.

I make it a habit not to delete entries in a foreach() loop. Rather, I
build an array of keys I want to delete, and after the loop ends, delete
the entries from my delete array.

I don't know whether an operation like this is guaranteed to work in PHP
- I've never seen it documented, so I suspect not. And just because it
works in one release under a certain set of conditions is not a
guarantee it will work on another release or under different conditions.
--
=============== ===
Remove the "x" from my email address
Jerry Stuckle
JDS Computer Training Corp.
js*******@attgl obal.net
=============== ===
May 19 '07 #5
On May 18, 9:05 pm, Jerry Stuckle <jstuck...@attg lobal.netwrote:
ZeldorBlat wrote:
On May 18, 11:40 am, "Jon Slaughter" <Jon_Slaugh...@ Hotmail.com>
wrote:
"ZeldorBlat " <zeldorb...@gma il.comwrote in message
>news:11******* **************@ p77g2000hsh.goo glegroups.com.. .
>On May 18, 11:05 am, "Jon Slaughter" <Jon_Slaugh...@ Hotmail.com>
wrote:
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 a temp array and
delete afterwards if necessary but since I'm actually working in a nested
situation this could get a little messy. I guess I could set there values
to
null and remove them afterwards?
Thanks,
Jon
Why don't you try it and see what happens?
Um... cause I did... but that doesn't mean much. Just cause someone tries
something doesn't prove that it will always work like that...
got any more bright ideas?
Or is the question to hard for you?
No, the question is not to (sic) hard for me. But, as you've already
discovered, it isn't that difficult to test, either.

Sorry, I agree with Jon on this one.

I make it a habit not to delete entries in a foreach() loop. Rather, I
build an array of keys I want to delete, and after the loop ends, delete
the entries from my delete array.

I don't know whether an operation like this is guaranteed to work in PHP
- I've never seen it documented, so I suspect not. And just because it
works in one release under a certain set of conditions is not a
guarantee it will work on another release or under different conditions.

--
=============== ===
Remove the "x" from my email address
Jerry Stuckle
JDS Computer Training Corp.
jstuck...@attgl obal.net
=============== ===
I never said I disagreed with him -- in fact I, too, generally don't
delete elements inside a foreach. However, I will say that when I
have done it things seem to work as expected. I guess it all comes
down to whether or not the array's internal pointer is modified when
you unset the element it's pointing to (I suspect it isn't).

I see a lot of questions in these newsgroups that look something like,
"What happens if I do X?" or "In PHP is this code valid?" The point I
was trying to make (and apparently Jon took offense to it) was that
it's easy enough to just try it and see what happens. Software is
just that: soft. It can be changed easily enough :)
May 19 '07 #6
ZeldorBlat wrote:
On May 18, 9:05 pm, Jerry Stuckle <jstuck...@attg lobal.netwrote:
>ZeldorBlat wrote:
>>On May 18, 11:40 am, "Jon Slaughter" <Jon_Slaugh...@ Hotmail.com>
wrote:
"ZeldorBla t" <zeldorb...@gma il.comwrote in message
news:11***** *************** *@p77g2000hsh.g ooglegroups.com ...
On May 18, 11:05 am, "Jon Slaughter" <Jon_Slaugh...@ Hotmail.com>
wrote:
>Is it safe to remove elements from an array that foreach is working on?
>(normall y this is not the case but not sure in php) If so is there an
>efficien t way to handle it? (I could add the indexes to a temp array and
>delete afterwards if necessary but since I'm actually working in a nested
>situatio n this could get a little messy. I guess I could set there values
>to
>null and remove them afterwards?
>Thanks,
>Jon
Why don't you try it and see what happens?
Um... cause I did... but that doesn't mean much. Just cause someone tries
something doesn't prove that it will always work like that...
got any more bright ideas?
Or is the question to hard for you?
No, the question is not to (sic) hard for me. But, as you've already
discovered, it isn't that difficult to test, either.
Sorry, I agree with Jon on this one.

I make it a habit not to delete entries in a foreach() loop. Rather, I
build an array of keys I want to delete, and after the loop ends, delete
the entries from my delete array.

I don't know whether an operation like this is guaranteed to work in PHP
- I've never seen it documented, so I suspect not. And just because it
works in one release under a certain set of conditions is not a
guarantee it will work on another release or under different conditions.

--
============== ====
Remove the "x" from my email address
Jerry Stuckle
JDS Computer Training Corp.
jstuck...@attg lobal.net
============== ====

I never said I disagreed with him -- in fact I, too, generally don't
delete elements inside a foreach. However, I will say that when I
have done it things seem to work as expected. I guess it all comes
down to whether or not the array's internal pointer is modified when
you unset the element it's pointing to (I suspect it isn't).

I see a lot of questions in these newsgroups that look something like,
"What happens if I do X?" or "In PHP is this code valid?" The point I
was trying to make (and apparently Jon took offense to it) was that
it's easy enough to just try it and see what happens. Software is
just that: soft. It can be changed easily enough :)

Yes, and in a case like this that change can break his code.

As I said - I've never seen it documented that this is valid. Maybe it
is and I missed it; I really don't know.

But this isn't the same as a lot of other "try it and find out"
questions. In this case it's a known problem in other programming
languages, and if it is documented that this should or should not work,
no one has pointed anyone to it.

And until I see something from the PHP developers saying it is OK, I
wouldn't do it.

--
=============== ===
Remove the "x" from my email address
Jerry Stuckle
JDS Computer Training Corp.
js*******@attgl obal.net
=============== ===
May 19 '07 #7
On May 18, 10:44 pm, Jerry Stuckle <jstuck...@attg lobal.netwrote:
ZeldorBlat wrote:
On May 18, 9:05 pm, Jerry Stuckle <jstuck...@attg lobal.netwrote:
ZeldorBlat wrote:
On May 18, 11:40 am, "Jon Slaughter" <Jon_Slaugh...@ Hotmail.com>
wrote:
"ZeldorBlat " <zeldorb...@gma il.comwrote in message
news:11***** *************** *@p77g2000hsh.g ooglegroups.com ...
On May 18, 11:05 am, "Jon Slaughter" <Jon_Slaugh...@ Hotmail.com>
wrote:
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 a temp array and
delete afterwards if necessary but since I'm actually working in a nested
situation this could get a little messy. I guess I could set there values
to
null and remove them afterwards?
Thanks,
Jon
Why don't you try it and see what happens?
Um... cause I did... but that doesn't mean much. Just cause someone tries
something doesn't prove that it will always work like that...
got any more bright ideas?
Or is the question to hard for you?
No, the question is not to (sic) hard for me. But, as you've already
discovered, it isn't that difficult to test, either.
Sorry, I agree with Jon on this one.
I make it a habit not to delete entries in a foreach() loop. Rather, I
build an array of keys I want to delete, and after the loop ends, delete
the entries from my delete array.
I don't know whether an operation like this is guaranteed to work in PHP
- I've never seen it documented, so I suspect not. And just because it
works in one release under a certain set of conditions is not a
guarantee it will work on another release or under different conditions.
--
=============== ===
Remove the "x" from my email address
Jerry Stuckle
JDS Computer Training Corp.
jstuck...@attgl obal.net
=============== ===
I never said I disagreed with him -- in fact I, too, generally don't
delete elements inside a foreach. However, I will say that when I
have done it things seem to work as expected. I guess it all comes
down to whether or not the array's internal pointer is modified when
you unset the element it's pointing to (I suspect it isn't).
I see a lot of questions in these newsgroups that look something like,
"What happens if I do X?" or "In PHP is this code valid?" The point I
was trying to make (and apparently Jon took offense to it) was that
it's easy enough to just try it and see what happens. Software is
just that: soft. It can be changed easily enough :)

Yes, and in a case like this that change can break his code.

As I said - I've never seen it documented that this is valid. Maybe it
is and I missed it; I really don't know.

But this isn't the same as a lot of other "try it and find out"
questions. In this case it's a known problem in other programming
languages, and if it is documented that this should or should not work,
no one has pointed anyone to it.

And until I see something from the PHP developers saying it is OK, I
wouldn't do it.

--
=============== ===
Remove the "x" from my email address
Jerry Stuckle
JDS Computer Training Corp.
jstuck...@attgl obal.net
=============== ===
This suggests that it's safe (from <http://www.php.net/foreach>):

"Unless the array is referenced, foreach operates on a copy of the
specified array and not the array itself. Therefore, the array pointer
is not modified as with the each() construct, and changes to the array
element returned are not reflected in the original array."

So unsetting a value in the original array should not affect the copy
that foreach is working on.

May 19 '07 #8
Jon Slaughter kirjoitti:
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 a temp array and
delete afterwards if necessary but since I'm actually working in a nested
situation this could get a little messy. I guess I could set there values to
null and remove them afterwards?
$a = range(0,10);
foreach($a as $key =$val)
if($val%2)
unset($a[$key]);

I've done something like this and have never had any problems. I don't
see the threats in this kind of thing, can you explain me what you think
that might be unsafe in this method?

--
Ra*********@gma il.com

"Wikipedia on vähän niinq internetin raamattu, kukaan ei pohjimmiltaan
usko siihen ja kukaan ei tiedä mikä pitää paikkansa." -- z00ze
May 19 '07 #9
At Fri, 18 May 2007 21:05:36 -0400, Jerry Stuckle let his monkeys type:
ZeldorBlat wrote:
>On May 18, 11:40 am, "Jon Slaughter" <Jon_Slaugh...@ Hotmail.com>
wrote:
>>"ZeldorBlat " <zeldorb...@gma il.comwrote in message

news:11****** *************** @p77g2000hsh.go oglegroups.com. ..

On May 18, 11:05 am, "Jon Slaughter" <Jon_Slaugh...@ Hotmail.com>
wrote:
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 a temp array and
delete afterwards if necessary but since I'm actually working in a nested
situation this could get a little messy. I guess I could set there values
to
null and remove them afterwards?
Thanks,
Jon
Why don't you try it and see what happens?
Um... cause I did... but that doesn't mean much. Just cause someone tries
something doesn't prove that it will always work like that...

got any more bright ideas?

Or is the question to hard for you?

No, the question is not to (sic) hard for me. But, as you've already
discovered, it isn't that difficult to test, either.

Sorry, I agree with Jon on this one.

I make it a habit not to delete entries in a foreach() loop. Rather, I
build an array of keys I want to delete, and after the loop ends, delete
the entries from my delete array.

I don't know whether an operation like this is guaranteed to work in PHP
- I've never seen it documented, so I suspect not. And just because it
works in one release under a certain set of conditions is not a
guarantee it will work on another release or under different conditions.
I agree 100% with you not to rely on undocumented 'features'.
Just out of curiosity I took this one step further and discovered the
following (again, can't rely on this to hold true unless it's documented
somewhere, well hidden):

<?PHP
$array=array('j ohn','james','d elilah','mary') ;
foreach ($array as $key=>$value) {
echo "$key =$value".NEWLIN E;
if ($value == 'delilah') {
$array[$key]='samson';
}
elseif ($value=='james ') {
unset($array[$key]);
}
}
echo NEWLINE;
foreach ($array as $key=>$value) {
echo "$key =$value".NEWLIN E;
}
?>
0 =john
1 =james
2 =delilah
3 =mary

0 =john
2 =samson
3 =mary

The foreach loop operates on a copy of the array
The original array remains in scope
Current($array) points to the first element throughout the loop

I'd think setting elements to NULL directly in the array isn't any better,
you're still relying on the same 'feature'.

Sh
May 19 '07 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

19
3695
by: deko | last post by:
I'm kind of lost on this one - I need to modify 2 files based on user input: $data_array = file($data_file); $counter_array = file($counter_file); // There is a line-for-line relationship between the data and counter files //for example, if the 3rd line in the counter file is deleted, //so also must the 3rd line of the data file be deleted. // Each line of the data_file has 4 items: //date|ip_address|user_id|url for ( $i=0; $i <...
8
2211
by: Generic Usenet Account | last post by:
To settle the dispute regarding what happens when an "erase" method is invoked on an STL container (i.e. whether the element is merely removed from the container or whether it also gets deleted in the process), I looked up the STL code. Erase certainly does not delete the memory associated with the element. However, it appears that the destructor on the element is invoked. I wonder why it has to be this way. In my opinion, this renders...
3
4763
by: Rik | last post by:
Hello, first of all, my provider sucks, newsserver is down for the #nth time now, offcourse when I have an urgent question.... So this will be me first time using Google Groups, forgive me if something goes wrong. The problem at hand: In a restricted area I let a user upload an image, no problem The image gets scaled down with imagecopyresampled(), and stored with imagejpeg($resized_img,'/path/to/target/image.jpg')
1
2310
by: kamal kothandaraman | 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 a temp array and delete afterwards if necessary but since I'm actually working in a nested situation this could get a little messy. I guess I could set there values to regards, K. Kothandaraman
3
2678
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' );
0
8768
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, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8690
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
9274
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, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
9139
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
7895
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, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6606
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5933
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4440
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
3138
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system

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.