Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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?

share|improve this question

closed as too localized by Rikesh, Gordon, hakre, DaveRandom, Jocelyn Mar 5 '13 at 12:10

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.If this question can be reworded to fit the rules in the help center, please edit the question.

1  
1  
possible duplicate of Access PHP array element with a function? –  Anirudh Ramanathan Aug 11 '12 at 5:47
    
The language doesn't allow it until 5.4.0 –  Toby Allen Aug 11 '12 at 6: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*/) );. –  Brian Graham Nov 17 '13 at 5:13

2 Answers 2

up vote 16 down vote accepted

You can't use function array dereferencing

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

until PHP 5.4.0 and above.

share|improve this answer
    
Ross got it first. Thanks, –  GraphicsResearch Aug 11 '12 at 5:54
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

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

share|improve this answer

Not the answer you're looking for? Browse other questions tagged or ask your own question.