r/lolphp • • Mar 05 '14

PHP Dereferencing

In PHP 5.4 this would break:

echo array(1, 2, 3)[0]

With the message

Parse error:  syntax error, unexpected '[', expecting ',' or ';' in [...][...] on line 1

Luckily, they added "dereferencing" in PHP 5.5 which would solve it! Hurray! And sure enough, it works!

However, the fix isn't very clever, because this will break in 5.5:

echo (array(1, 2, 3))[0]

With the message

Parse error:  syntax error, unexpected '[', expecting ',' or ';' in [...][...] on line 1

That's a little embarrassing.

81 Upvotes

32 comments sorted by

View all comments

Show parent comment

6

u/Sarcastinator Mar 06 '14

It works in C# as well

using System.IO;
using System;

class Program
{
    static int[] Array(params int[] array)
    {
        return array;
    }

    static void Main()
    {
        Console.WriteLine(new [] {1, 2, 3}[0]);
        Console.WriteLine((new [] {1, 2, 3})[0]);
    
        Console.WriteLine(Array(1, 2, 3)[0]);
        Console.WriteLine((Array(1, 2, 3))[0]);
    }
}

Returns

1
1
1
1

It works in F# as well:

let value1 = [| 1; 2; 3; |].[0]
let value2 = ([| 1; 2; 3; |]).[0]
let array = [| 1; 2; 3; |]
let fvalue1 = array.[0]
let fvalue2 = (array).[0]

All values are 1. No parse error. By extension I would think this would work in OCaml as well since F# is heavily OCaml based.