php - function()[] syntax

57 views Asked by At

I have a strange syntax problem in php.

At some point in my code, I do a mysql query (which only send back one line with one value), and I get the query result the following way :

$myvar = mysql_fetch_assoc($result)["something"];

$result being the mysql result, of course. It works just fine, both locally and on the site. However, when my colleague took the latest version of the site for some local test of his own, he got the following error :

Parse Error: syntax error, unexpected '[' in C:\wamp\www\mySite\ref\myFile.php on line 33

Line 33 being the line where I defined $myvar. He fixed it by doing the following :

$myvar = mysql_fetch_assoc($result);
$myvar = $manif["something"];

It seems pretty obvious to me that the problem comes from wamp (I am personally running an apache server), so my question is "why?".

I only got into web development recently (I was more of a C++ developer until now) and I've been using this syntax for a while. Is it bad practice?

And why does wamp return an error but not apache? Do each server have their own php parser?

Thank you.

2

There are 2 answers

0
Thomas Ruiz On

Function array dereferencing (foo()[0] for example) has been introduced in PHP5.4. Check your php version.

0
Kristian Vitozev On

Since PHP 5.4 it's possible to do what you want. If you colleague use older version of PHP, that's why it's not working.

If you are using PHP prior to 5.3, you should use temporary variable, e.g. something like this:

$r = mysql_fetch_assoc($result);

$myvar = $r['something'];