14
ZioCain
5y

I swear I NEVER hated PHP before, but after seeing this shit, I just can't love it anymore, I feel betrayed

I mean, WTF? Just bc I'm using the variable as a reference in the NEXT loop the LAST element changes? What even is the fucking reason?

Yeah, I read the answer on StackOverflow, but seriously...

SO ref: https://stackoverflow.com/questions...

Comments
  • 9
    It's kinda a bug, but it's also a reference in memory issue too, which is why I very rarely use variables by reference in php unless it's to conserve memory limits which I can't get around.

    Basically, and if I go look at that link it's probably safe to say it says the same thing, you no longet have a localised variable for the scope of the foreach() as you pushed it as a reference giving the second $item an inherited value, you should unset() the first $item

    Also, can you do my eyes a favour and hit the Enter key just before that ")" in your first array?
  • 1
    wait php doesn't use reference types like all the sane high level languages??
  • 1
    @inaba IIRC they are only value types and "references" which are actually aliases
  • 3
    My problem here is that $item is not scoped to the foreach. That really drives me nuts. That would make this behavior impossible and is in general what you actually expect.
  • 1
    @Lythenas indeed!

    Bc rn all that can be done is using "unset($item)" after the first loop
  • 1
    @C0D4 I'm sorry about how that's written, I just screenshotted the question on SO.
  • 2
    @12bitfloat https://php.net/manual/en/...

    > One of the key-points of PHP 5 OOP that is often mentioned is that "objects are passed by references by default".

    Well that is how it's supposed to be I gue-

    > This is not completely true. This

    Oh- oh god
  • 0
    Never had to use such a foreach loop. Why care
  • 1
    @inaba I've generally gotten the impression that mistaking PHP for a sane language can lead to much mental anguish, and I've never used PHP. It's really it's own thing, design-wise.
  • 1
    It is not a bug. Read the accepted answer for the technical explanation.

    If you want to avoid this, just use a different name for your references.

    foreach($arr as &$ref) { ... } print_r($arr);

    foreach($arr as $val) { ... } print_r($arr);
  • 0
    @nitnip I know I know, it's just that is not how most people think it should work
  • 2
    @nitnip "It's not a bug, it's just really stupid"
Add Comment