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.

This question already has an answer here:

PHP Syntax Check: Parse error: syntax error, unexpected '[' in your code on line 100

$clicks = each( $array )[1];

is this the correct syntax? (apologies for the noob question)

$clicks = each( $array [1]);

From section:

$array = array_count_values( $array );
        unset( $array[''] );
        do
        {
            $clicks = each( $array )[1];
            $id = each( $array )[0];
            if ( each( $array ) )
            {
            }
share|improve this question

marked as duplicate by John Conde, andrewsi, Chris, jkschneider, Ian Feb 17 '14 at 2:45

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

    
Which one throws an error, which done does not? –  Daryl Gill Nov 9 '13 at 22:23
3  
What version of PHP are you using? Array dereferencing was introduced in 5.4.... but $clicks = each( $array )[1]; and $clicks = each( $array [1]); would achieve totally different things. What are you actually trying to do? –  Mark Baker Nov 9 '13 at 22:24
    
Well $clicks = each( $array )[1]; is throwing the error, so I assume that would never be correct. But I'm using 5.2. If I comment out that line, the following line causes the error, so it has to be that the brackets are exposed, no? –  Potatrick Nov 9 '13 at 22:33

2 Answers 2

up vote 0 down vote accepted

In the latest version of PHP that's fine, for backward compatibility, I recommend something like:

$clicks = each($array); $click = $clicks[1];

Now use $click instead of $clicks, in your code below.

share|improve this answer

You'd probably be better to use a foreach ($array as $key=>$val){ // do your logic here)} for array traversal, or if you want to use each's return, store it in a separate variable first, then reference the key you want.

ie:

$eachResult = each($array);
$clicks=$eachResult[1];
$id=$eachResult[0];
...

The ability to use [ ] to reference an array key of a function returning an array was only added in a very recent version of php. (5.4 I believe).

edit: Yep, 5.4: "Function array dereferencing has been added, e.g. foo()[0]."

http://www.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.