0

The conventional way of doing this would be

$row = mysql_fetch_array($query);
echo $row['column'];

but I would like to know if it is possible to do something like

echo mysql_fetch_array($query)['column'];

I tried doing this on my local installation, but I get this error:

Parse error: syntax error, unexpected '[', expecting ',' or ';' in C:\Program Files (x86)\EasyPHP\www\array.php on line 5

This is mainly to reduce the number of lines in my code, as I'm writing a function that places a lot of mysql results into variables, and I don't want to have code that looks like

$row = ...
$this->data[] = $row[];
$row = ...
$this->data[] = $row[];
...and so on
3
  • That syntax function()['arraykey'] is called array dereferencing, and it is possible in the newly released PHP 5.4, but not in earlier versions. Commented Mar 31, 2012 at 23:21
  • Just looked that up, thanks. My easyphp installation is running 5.3.9 :S Commented Mar 31, 2012 at 23:23
  • 2
    Reducing number of lines does not always equal improved code. You also need to consider the readability of the code. Commented Mar 31, 2012 at 23:23

1 Answer 1

4

You can use mysql_fetch_object() instead:

echo mysql_fetch_object($query)->column;

You can also use mysql_result() to retrieve a single field from the resultset:

echo mysql_result($query, 0, 'column');

Both cases are highly inappropriate though if you want to access more than a single column per row..

Sign up to request clarification or add additional context in comments.

1 Comment

Well since he's not using it in a loop he probably has only one row anyway. When looping not assigning the row to a variable would just result in very ugly code...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.