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
1  
possible duplicate of Access PHP array element with a function? – Cthulhu Aug 11 '12 at 5:47
The language doesn't allow it until 5.4.0 – Toby Allen Aug 11 '12 at 6:19
feedback

2 Answers

up vote 4 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, – Ian Mallett Aug 11 '12 at 5:54
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 at 19:41
feedback

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
feedback

Your Answer

 
or
required, but never shown
discard

By posting your answer, you agree to the privacy policy and terms of service.

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