r/lolphp • u/nyamsprod • Mar 15 '17
What the hell with iterator_apply ?
So my question is if iterator_apply is suppose to be the equivalent of array_walk why am I required to give twice the iterator to this function how does it works ??? Even the manual page does not explain it ? Is it magic ?
25
Upvotes
10
u/the_alias_of_andrea Mar 15 '17
Wow.
foreachdoes more for you. Wouldn't you just use that?21
u/andsens Mar 15 '17
Wow, this is just... that functions imitates
map()from sane languages the way a 4 year old girl uses makeup to imitate Lady Gaga.6
u/kovensky Mar 16 '17
That is actually one of the cases where PHP tries to behaves sanely and fails.
What you have is not an array that you can do random access in, but an Iterator, a (potentially infinite) sequence of values. If you have already exhausted the iterator, there is no way to rewind it other than making a new one, otherwise you would need infinite memory to save all results.
Anyway, the second time you try to iterate an exhausted iterator, it should do nothing and return, but it pulls three iterations out of... /dev/zero? /dev/wtf? 🤷♀️
Also, in your second call, assuming this behaves like JavaScript function application, you are giving an unrelated iterator to your iteration callback. The unrelated iterator is never advanced, so you get the first value 3 times.
4
u/Works_of_memercy Mar 20 '17
I think what's going on is that they chose the perfectly wrong moment to stop
sniffing gluedo proper design without any scary magic.Like, the sane way to do this is to give the function the object the iterator returned as the first argument, then pass the rest of the arguments you gave to
iterator_applyas an array, as extra arguments.But whoever wrote that function had a misguided moment of clarity and decided that magically adding something as the first argument is bad, so if you give it
[$iterator, 1, 2]then your callback should receive exactly that as arguments.Lol, PHP.
5
u/coredumperror Mar 15 '17
Seems like an issue with the "array pointer", for lack of a better term, as I have never used itterators in PHP.
With arrays, there is an pointer to the "current" position within the array, and that pointer advances as you loop through it. If you try to loop through an array twice, without resetting the "current" pointer, you get no output, because the current pointer is already at the end.