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?

4
  • 3
    That's a PHP syntax limitation. Only PHP 5.4 will allow that. Commented May 13, 2012 at 0:44
  • @bfavaretto, Is there anything I can read about it? Are there other things like this? Commented May 13, 2012 at 0:44
  • I couldn't find much, but check this: wiki.php.net/rfc/functionarraydereferencing Commented May 13, 2012 at 0:47
  • You could use either $cnt = mysql_result(mysql_query("SELECT FOUND_ROWS()")),0) or $cnt = current(mysql_fetch_row(mysql_query("SELECT FOUND_ROWS()"))). Commented May 13, 2012 at 0:48

1 Answer 1

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];
Sign up to request clarification or add additional context in comments.

5 Comments

That's annoying -.- Is there a reason for it?
That's the million-dollar question for an awful lot of PHPisms :^)
@Walkerneo No, not really. As already mentioned by bfavaretto, it's been fixed in 5.4. PHP has many oddities like this.
@Walkerneo I suppose you have to continue to dig if you want more info, but the reason 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."

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.