0

I find myself creating redundant variables in PHP when querying the database.

In Javascript, C# and Java I'm able to directly use an array index operator after a method call, where as in PHP, I can't.

The following example illustrates my point:

// $result -> SELECT t.id
//            FROM table t
//            WHERE t.name = 'bla'
//            LIMIT 1    

$o = mysql_fetch_assoc($result);
$value = $o['valueIndex'];

And this would be invalid:

$value = mysql_fetch_assoc($result)['valueIndex'];

Why is the above invalid, did they do this by design? Or would the grammar get too complicated?

Little fiddle over here.

Kevin
  • 5,626
  • 3
  • 28
  • 41
  • 3
    It seems to be coming to PHP: [Interpreting return value of function directly as an array](http://stackoverflow.com/q/5781360) – Pekka May 13 '11 at 08:08
  • try `(mysql_fetch_assoc($result))['valueIndex'];` just an idea. – ahmet alp balkan May 13 '11 at 08:08
  • possible duplicate of [PHP syntax for dereferencing function result](http://stackoverflow.com/questions/742764/php-syntax-for-dereferencing-function-result) – deceze May 13 '11 at 08:09
  • This is just how PHP work. You cannot use method call as array. This is sad, but the things are going to change in new PHP version (6 or 5.4), so this would be possible – Ventus May 13 '11 at 08:10
  • I'm voting to close this as a duplicate because @salathe's answer in the other question answers your question in full (including links to php internal discussion). – Pekka May 13 '11 at 08:10
  • possible duplicate of [PHP use function return value as array](http://stackoverflow.com/questions/2851465/php-use-function-return-value-as-array) – Pekka May 13 '11 at 08:11
  • @Pekka - You're right, that question contains the information I wanted to know, but, why hasn't this been implemented sooner? – Kevin May 13 '11 at 08:12

2 Answers2

4

This will be implemented in PHP 5.4 as it stands currently.

In your specific case you can use following workaround for now:

$value = mysql_fetch_object($result)->valueIndex;

While array derefencing wasn't a planned PHP feature, object access is always possible for function results.

mario
  • 144,265
  • 20
  • 237
  • 291
0

This should work shouldn't it?

$value = (mysql_fetch_assoc($result))['valueIndex'];

Craig White
  • 13,492
  • 4
  • 23
  • 36
  • I retract my comment then. What is wrong with simply using two lines for a query? What happens if you'd like to reuse that fetched array? I'd simply do it the first way. – Craig White May 13 '11 at 08:13