3

Possible Duplicate:
Access array returned by a function in php

The code:

$cnt = mysql_fetch_row(mysql_query("SELECT FOUND_ROWS()"))[0]

Is giving the error:

Parse error: syntax error, unexpected '[' in index.php on line 117

Same for:

$cnt = (mysql_fetch_row(mysql_query("SELECT FOUND_ROWS()")))[0]

This code:

$cnt = mysql_fetch_row(mysql_query("SELECT FOUND_ROWS()"));
$cnt = $cnt[0];

is working fine.

What's going on here?

Community
  • 1
  • 1
mowwwalker
  • 16,634
  • 25
  • 104
  • 157

1 Answers1

4

It isn't just a problem with mysql_query--rather, it's an idiosyncracy in the way that PHP <5.4 handles bracket notation. The following will fail, as well:

function get_array() {
  return array('foo', 'bar');
}

echo get_array()[0];

But, as you observed, setting the result before attempting to retrieve an element works fine:

$arr = get_array();
echo $arr[0];
rjz
  • 16,182
  • 3
  • 36
  • 35
  • That's annoying -.- Is there a reason for it? – mowwwalker May 13 '12 at 00:45
  • 1
    That's the million-dollar question for an awful lot of PHPisms :^) – rjz May 13 '12 at 00:46
  • @Walkerneo No, not really. As already mentioned by bfavaretto, it's been fixed in 5.4. PHP has many oddities like this. – kba May 13 '12 at 00:46
  • 1
    [Array dereferencing](http://php.net/manual/en/migration54.new-features.php) – PeeHaa May 13 '12 at 00:47
  • @Walkerneo I suppose you have to continue to dig if you want more info, but [the reason](http://schlueters.de/blog/archives/138-Features-in-PHP-trunk-Array-dereferencing.html) claims to be that this patch was rejected for a long time because "due to uncertainties about memory issues, as we don't like memory leaks." – chrisn May 13 '12 at 00:49