2

So, this is not a problem than need solving, but rather a question out of curiosity and want of clarification. A was struggling with a piece of php/mysqli and while debugging and splitting the code up I discovered that my code was working, just not the way I wrote it.

Initial code (Not working)

$result = $mysqli -> query("SELECT nick FROM userdata WHERE id=".$_SESSION['uid']);
// ... error checking here ...
for($i = $result -> num_rows - 1; $i >= 0; $i--){
    $result -> data_seek($i);
    $nick = ($result -> fetch_assoc())['nick']; // crash
}

Final code (Working)

$result = $mysqli -> query("SELECT nick FROM userdata WHERE id=".$_SESSION['uid']);
// ... error checking here ...
for($i = $result -> num_rows - 1; $i >= 0; $i--){
    $result -> data_seek($i);
    $row = $result -> fetch_assoc(); // working
    $nick = $row['nick']; // working
}

So, can anyone enlighten me as to why the first code simply breaks for me?

Best regards.

Anton
  • 1,435
  • 2
  • 10
  • 21
  • 3
    PHP's compiler can't handle the syntax in the first case, except in recent versions. See http://stackoverflow.com/questions/1459377/access-array-returned-by-a-function-in-php – Waleed Khan Oct 06 '13 at 18:52

1 Answers1

5

PHP 5.4 (2012-03-01) and later versions support array dereferencing from a function call.

See http://php.net/manual/en/language.types.array.php

As of PHP 5.4 it is possible to array dereference the result of a function or method call directly. Before it was only possible using a temporary variable.

As of PHP 5.5 it is possible to array dereference an array literal.

Then it shows examples. See Example #7 on that page.

Community
  • 1
  • 1
Bill Karwin
  • 538,548
  • 86
  • 673
  • 828