Why can't I index the mysql returned array?

Possible duplicate:
Access array returned by function in php

The code:

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

Gives an error message:

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

The same goes 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];

works fine.

What's going on here?

+3
source share
1 answer

This is not just a problem with mysql_query- rather, this idiosyncrasy is that PHP <5.4 handles the bracket notation. The following also does not work :

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

echo get_array()[0];

But, as you noticed, setting the result before trying to extract the item works fine :

$arr = get_array();
echo $arr[0];
+4
source

All Articles