5

end(array_keys(array(0))) says PHP Strict standards: Only variables should be passed by reference ( http://3v4l.org/CNLVT )

end((array_keys(array(0)))) on the other hand, just works ( http://3v4l.org/168fi ). Why?

The VLD decompiler shows the same opcodes being ran the only difference is in the ext column but I can't find documentation on what that means.

chx
  • 11,270
  • 7
  • 55
  • 129
  • There is a similar trick in MySQL where you can't update a table a select from the same table ([see this answer](http://stackoverflow.com/questions/12475850/how-can-an-sql-query-return-data-from-multiple-tables/12508381#12508381) - the second bit of the answer) but it revolves around how the evaluated data is being passed. Sticking an extra set of brackets around it changes the way it is treated. It's something about the value coming directly from a function vs being treated as it's own entity inside the brackets. – Fluffeh May 18 '14 at 12:57
  • Heh, @NikiC, I was just about to do that ::D – Lightness Races in Orbit May 18 '14 at 13:04

1 Answers1

2

What's likely happening is array_keys is passing the result back by reference. As such, PHP is throwing you a notice that you shouldn't do that.

Wrapping in parenthesis actually changes the reference and forces PHP to evaluate the statement inside first. As such, it removes the reference. One of those weird things that doesn't look like it makes a difference but actually does.

More on the weirdness here http://phpsadness.com/sad/51

Machavity
  • 30,841
  • 27
  • 92
  • 100
  • What I said, but much better, clearer and understandable :) +1 – Fluffeh May 18 '14 at 13:03
  • 4
    `array_keys` definitely does not pass the result back by reference and even the error indicates the *exact opposite*. This is not the correct answer! – chx May 18 '14 at 13:06
  • @Fluffeh don't be jealous ;P – itachi May 18 '14 at 13:07
  • 2
    @chx actually it does. "only variables should be passed by reference" means the result _is_ being passed by reference - but (because of implementation details) is not a variable. – AD7six May 18 '14 at 13:08
  • 1
    There's an [interesting comment](http://www.php.net/manual/en/function.array-keys.php#113521) in the function reference on this very question, actually – Machavity May 18 '14 at 13:09
  • @Machavity Jealous? Not at all - just one of those enjoyable moments when a really good question is asked and I know the answer. In this case, I didn't know how to express it as well as you did (hence I left a comment not an answer) but still knowing makes me feel good :) – Fluffeh May 18 '14 at 13:14