Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP Array Syntax Parse Error Left Square Bracket "[" [closed]

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?

like image 853
imallett Avatar asked Aug 11 '12 05:08

imallett


People also ask

What is a [] in PHP?

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.

How do I fix parse error syntax error?

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.

What are square brackets in PHP?

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.

What is PHP parse error?

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.


2 Answers

You can't use function array dereferencing

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

until PHP 5.4.0 and above.

like image 118
Ross Smith II Avatar answered Oct 17 '22 05:10

Ross Smith II


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

like image 33
M. Ahmad Zafar Avatar answered Oct 17 '22 07:10

M. Ahmad Zafar