473,837 Members | 1,888 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
29 4264
At Sun, 20 May 2007 10:23:31 -0400, Jerry Stuckle let his monkeys type:
>>>>
I'd think setting elements to NULL directly in the array isn't any
better,
you're still relying on the same 'feature'.

Sh
Yes, foreach() works on a copy. But while the manual indicates changes to
the copy don't affect the original - they say nothing about when changes
to the original will affect the copy.

since its a copy the original should effect in any way the copy?

I could only see this if the copy is not a deep copy.... but in php all
copies are deep?


There is nothing indicating when the copy is updated from the original.
It might be only at the beginning, everything through the loop or
anything else.

It's not documented - so you can't depend on the operation.
In fact, there may be a hint the array behaviour isn't as straightforward
as it seems in this case. Good point Jerry. As in this example:
http://www.thescripts.com/forum/thread631554.html where it appears at
least the array pointer (which seemed unaffected in my earlier test)
doesn't behave completely as one would expect if a foreach operated on a
totally isolated array copy.

Sh.
May 20 '07 #21
On 20.05.2007 05:09 Jon Slaughter wrote:
>
Well, your right. I assume that when it says copy it means a deep copy. If
so then essentially its working on a different variable...
From my understanding, foreach doesn't make a copy of *entire array*,
it just copies *current value* into the loop variable (unless you
provided it by reference).
>
If it was C/C++ then you would definitely have to worry about that sorta
stuff and chances are would have to buffer the deletes or use some other
method unless you can be absolutely sure its a deep copy.

The more one dives into these sorta of things the more vague the solution
is. It should be completely spelled out in the manual but its not ;/ These
times of issues usually are a big deal and technically one can't assume
anything but its working and I'm about 95% sure that I'm right in the way it
works so I'm just going to assume that until otherwise. Obviously no one
really seems to know the answer completely it seems ;/
I understand your concerns. Deleting elements in a loop might be
technically ok, but it just feels unsafe. Essentially what you're doing
is filtering and it'd better to write it as such:

$good = array();
foreach($ary as $elem)
if(my_check_fun c($elem)) $good[] = $elem;

or simply

$good = array_filter($a ry, 'my_check_func' );
--
gosha bine

extended php parser ~ http://code.google.com/p/pihipi
blok ~ http://www.tagarga.com/blok
May 21 '07 #22
gosha bine kirjoitti:
On 20.05.2007 05:09 Jon Slaughter wrote:
>>
Well, your right. I assume that when it says copy it means a deep
copy. If so then essentially its working on a different variable...

From my understanding, foreach doesn't make a copy of *entire array*,
it just copies *current value* into the loop variable (unless you
provided it by reference).
Here's a way to test it:

<?php

$a = range(0,4);

foreach($a as $k =$v){
if(isset($a)) unset($a);
echo "$k =$v<br>";
}

print_r($a);

?>

To me it would seem the entire array is copied, since it prints all the
values even after the array is unset, I got the output:
0 =0
1 =1
2 =2
3 =3
4 =4

--
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 21 '07 #23
On 21.05.2007 18:00 Rami Elomaa wrote:
gosha bine kirjoitti:
>On 20.05.2007 05:09 Jon Slaughter wrote:
>>>
Well, your right. I assume that when it says copy it means a deep
copy. If so then essentially its working on a different variable...

From my understanding, foreach doesn't make a copy of *entire array*,
it just copies *current value* into the loop variable (unless you
provided it by reference).

Here's a way to test it:

<?php

$a = range(0,4);

foreach($a as $k =$v){
if(isset($a)) unset($a);
echo "$k =$v<br>";
}

print_r($a);

?>

To me it would seem the entire array is copied, since it prints all the
values even after the array is unset, I got the output:
0 =0
1 =1
2 =2
3 =3
4 =4
Good point. Here's another example for even deeper meditation

$a = range(0,4);
// $b = &$a;
foreach($a as $k =$v){
$a[99] = 5;
echo "$k=>$v\n";
}

(try uncommenting the second line).


--
gosha bine

extended php parser ~ http://code.google.com/p/pihipi
blok ~ http://www.tagarga.com/blok
May 21 '07 #24
Rami Elomaa wrote:
gosha bine kirjoitti:
>On 20.05.2007 05:09 Jon Slaughter wrote:
>>>
Well, your right. I assume that when it says copy it means a deep
copy. If so then essentially its working on a different variable...

From my understanding, foreach doesn't make a copy of *entire array*,
it just copies *current value* into the loop variable (unless you
provided it by reference).

Here's a way to test it:

<?php

$a = range(0,4);

foreach($a as $k =$v){
if(isset($a)) unset($a);
echo "$k =$v<br>";
}

print_r($a);

?>

To me it would seem the entire array is copied, since it prints all the
values even after the array is unset, I got the output:
0 =0
1 =1
2 =2
3 =3
4 =4
Rami,

That may be true on the release you're running at. But is it true for
all releases? And will it remain that way? Unless it's documented to
work that way, there's no way of telling.

And these are exactly the types of assumptions which get you in deep
trouble.
--
=============== ===
Remove the "x" from my email address
Jerry Stuckle
JDS Computer Training Corp.
js*******@attgl obal.net
=============== ===
May 21 '07 #25
Jerry Stuckle kirjoitti:
Rami Elomaa wrote:
>gosha bine kirjoitti:
>>On 20.05.2007 05:09 Jon Slaughter wrote:
Well, your right. I assume that when it says copy it means a deep
copy. If so then essentially its working on a different variable...

From my understanding, foreach doesn't make a copy of *entire
array*, it just copies *current value* into the loop variable (unless
you provided it by reference).

Here's a way to test it:

<?php

$a = range(0,4);

foreach($a as $k =$v){
if(isset($a)) unset($a);
echo "$k =$v<br>";
}

print_r($a);

?>

To me it would seem the entire array is copied, since it prints all
the values even after the array is unset, I got the output:
0 =0
1 =1
2 =2
3 =3
4 =4

Rami,

That may be true on the release you're running at. But is it true for
all releases? And will it remain that way? Unless it's documented to
work that way, there's no way of telling.
I agree that if it is documented you can't trust it. However, looking at
http://fi2.php.net/manual/en/control...es.foreach.php you'll find
the following: "Note: Unless the array is referenced, foreach operates
on a copy of the specified array and not the array itself." Wouldn't
that make this a _documented_ feature that you can actually rely on?

--
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 21 '07 #26
Rami Elomaa wrote:
Jerry Stuckle kirjoitti:
>Rami Elomaa wrote:
>>gosha bine kirjoitti:
On 20.05.2007 05:09 Jon Slaughter wrote:

>
Well, your right. I assume that when it says copy it means a deep
copy. If so then essentially its working on a different variable...

From my understanding, foreach doesn't make a copy of *entire
array*, it just copies *current value* into the loop variable
(unless you provided it by reference).

Here's a way to test it:

<?php

$a = range(0,4);

foreach($a as $k =$v){
if(isset($a)) unset($a);
echo "$k =$v<br>";
}

print_r($a) ;

?>

To me it would seem the entire array is copied, since it prints all
the values even after the array is unset, I got the output:
0 =0
1 =1
2 =2
3 =3
4 =4

Rami,

That may be true on the release you're running at. But is it true for
all releases? And will it remain that way? Unless it's documented to
work that way, there's no way of telling.

I agree that if it is documented you can't trust it. However, looking at
http://fi2.php.net/manual/en/control...es.foreach.php you'll find
the following: "Note: Unless the array is referenced, foreach operates
on a copy of the specified array and not the array itself." Wouldn't
that make this a _documented_ feature that you can actually rely on?

--
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
Yes, but that wasn't the original question.

The original question was - is it safe to delete from the original array
while in a foreach() loop? The answer to this is still no - there is no
indication what happens with the copy when the original is changed.

--
=============== ===
Remove the "x" from my email address
Jerry Stuckle
JDS Computer Training Corp.
js*******@attgl obal.net
=============== ===
May 21 '07 #27
At Mon, 21 May 2007 19:39:43 +0200, gosha bine let his monkeys type:

Good point. Here's another example for even deeper meditation

$a = range(0,4);
// $b = &$a;
foreach($a as $k =$v){
$a[99] = 5;
echo "$k=>$v\n";
}

(try uncommenting the second line).
Yikes. Nice. Now let us get this straight. By referencing ($b = &$a)
suddenly the foreach loop becomes aware of changes in $a. Tricky.

Any solid ideas how this works internally? I'd say it suggests
PHP's reference model isn't really based on references for one. But I may
be wrong. A real headscratcher. And this proves Jerry's point once again:
don't trust anything that's not explicitly stated in detail in the
documentation.

Just for fun, a candidate for 'most original and idiotic endless
memory gobbling loop':
$a = range(0,4);
$b = &$a;
$cnt=2;
foreach($a as $k =$v){
$a[$cnt++] = 5;
echo "$k=>$v\n";
}

Weird thing is it doesn't even produce an error on my box. It just stops
(I do assume however this is due to memory running out)

Again, impressive albeit academic find, Gosha. Worth a bug report you
think? Sh.
May 21 '07 #28
On 21.05.2007 22:28 Schraalhans Keukenmeester wrote:
At Mon, 21 May 2007 19:39:43 +0200, gosha bine let his monkeys type:

>Good point. Here's another example for even deeper meditation

$a = range(0,4);
// $b = &$a;
foreach($a as $k =$v){
$a[99] = 5;
echo "$k=>$v\n";
}

(try uncommenting the second line).

Yikes. Nice. Now let us get this straight. By referencing ($b = &$a)
suddenly the foreach loop becomes aware of changes in $a. Tricky.

Any solid ideas how this works internally?
Internally, foreach is a pair of FE_RESET (start loop) and FE_FETCH
(iteration) opcodes, implementation of FE_RESET starts here

http://lxr.php.net/source/ZendEngine..._vm_def.h#3191

note the line 3219
(http://lxr.php.net/source/ZendEngine..._vm_def.h#3219)

SEPARATE_ZVAL_I F_NOT_REF(array _ptr_ptr);
It basically says: "separate ZVAL" (i.e. make a copy) of the array
(array_ptr_ptr) only if it is not a reference. That is, Rami was right
about copying, but it only takes place when the array is a "normal"
variable, not a reference.
<...>
Again, impressive albeit academic find, Gosha. Worth a bug report you
think? Sh.
I'm kind of reluctant to upset the good people ;) therefore I'd refrain
from reporting this. Maybe you? ;)
--
gosha bine

extended php parser ~ http://code.google.com/p/pihipi
blok ~ http://www.tagarga.com/blok
May 22 '07 #29
In article <f2*********@ny ytiset.pp.htv.f i>, Rami Elomaa wrote:
$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?
Unless I'm mistaken the potential problem lies in the possibility that the array
is indexed in such a way that, if you delete elements from it whilst something
(in this case "foreach" is working through it, the index that foreach is using
might be compromised and so the next iteration might not return the element that
the programmer was expecting.

The easiest way to see this occurring is to use a numeric index into the array,
*then* delete something from the middle of it whilst in a loop.
Good question Jon! 8-)

Regards
Mark
May 22 '07 #30

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

Similar topics

19
3705
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
2221
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
4768
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
2317
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
2687
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
9846
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
9686
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
10890
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...
1
10634
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9416
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
7819
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
7007
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();...
2
4053
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
3127
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.