14

I have a function that returns an array. I have another function that just returns the first row, but for some reason, it makes me use an intermediate variable, i.e. this fails:

function f1(/*some args*/) {
    return /*an array*/;
}
function f2(/*some args*/) {
    return f1(/*some args*/)[0];
}

. . . with:

Parse error: syntax error, unexpected '[' in util.php on line 10

But, this works:

function f1(/*some args*/) {
    return /*an array*/;
}
function f2(/*some args*/) {
    $temp = f1(/*some args*/);
    return $temp[0];
}

I wasn't able to find anything pertinent online (my searches kept getting confused by people with "?", "{", "<", etc.).

I'm self-taught in PHP - is there some reason why I can't do this directly that I've missed?

Don
  • 863
  • 1
  • 8
  • 22
geometrian
  • 14,775
  • 10
  • 56
  • 132
  • 1
    possible duplicate of [Is it possible to reference a specific element of an anonymous array in PHP?](http://stackoverflow.com/questions/8276224/is-it-possible-to-reference-a-specific-element-of-an-anonymous-array-in-php) – DCoder Aug 11 '12 at 05:41
  • 1
    possible duplicate of [Access PHP array element with a function?](http://stackoverflow.com/questions/396519/access-php-array-element-with-a-function) – Anirudh Ramanathan Aug 11 '12 at 05:47
  • The language doesn't allow it until 5.4.0 – Toby Allen Aug 11 '12 at 06:19
  • Even though this is old, I thought I'd leave a comment. You can return index 0 if you use `current`, like so: `return current( f1(/*some args*/) );`. – Nahydrin Nov 17 '13 at 05:13

2 Answers2

25

You can't use function array dereferencing

return f1(/*some args*/)[0];

until PHP 5.4.0 and above.

Michael Hampton
  • 9,737
  • 4
  • 55
  • 96
Ross Smith II
  • 11,799
  • 1
  • 38
  • 43
  • 1
    props for revealing the proper term for this, it ended a long search for what should have been a simple question. – Adam Tolley Jan 24 '13 at 19:41
2

The reason for this behavior is that PHP functions can't be chained like JavaScript functions can be. Just like document.getElementsByTagNames('a')[0] is possible.

You have to stick to the second approach for PHP version < 5.4

Function array dereferencing has been added, e.g. foo()[0].

http://php.net/manual/en/migration54.new-features.php

M. Ahmad Zafar
  • 4,881
  • 4
  • 32
  • 44