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?
In many languages the [] notation stands for an array. Is the same as php's array_push() : it pushes an element in the variable that has [] at the end. If the variable is null, you can consider the square brackets like a declaration of an array.
A parse error: syntax error, unexpected appears when the PHP interpreter detects a missing element. Most of the time, it is caused by a missing curly bracket “}”. To solve this, it will require you to scan the entire file to find the source of the error.
In PHP, elements can be added to the end of an array by attaching square brackets ([]) at the end of the array's name, followed by typing the assignment operator (=), and then finally by typing the element to be added to the array.
If the PHP code contains a syntax error, the PHP parser cannot interpret the code and stops working. For example, a syntax error can be a forgotten quotation mark, a missing semicolon at the end of a line, missing parenthesis, or extra characters.
You can't use function array dereferencing
return f1(/*some args*/)[0];
until PHP 5.4.0 and above.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With