Why is it possible to access array indexes with "{}" keys?

Asked

Viewed 107 times

5

In some tests I did with PHP, I saw that it is possible to use keys ({}) to access indexes of arrays.

Example:

$array = ['a' => 1, 'b' => 2, 'c' => ['d' => 4]]

echo $array{'c'}{'d'}; // 4
echo $array{'c'}['d']; // 4

Until then, I thought only the brackets ([]) did this.

So I want to ask:

  • Access an index of a array with keys instead of brackets has some special meaning?

  • Why is it possible to use both forms?

  • Would using keys be considered out of the standard? I ask this because, although it works, I’ve never seen anyone using.

  • 4

    http://php.net/manual/en/language.types.array.php#example-61 See the note a little below the example.

  • http://answall.com/questions/77693/qual%C3%A9-a-utility-to-declare-Vari%C3%A1veis-atrav%C3%A9s-to-braces (I’m not saying it’s duplicate)

  • @Danielomine may not be duplicated, but it’s very similar.

1 answer

5


Accessing an index of an array with keys instead of brackets has some special meaning?

Not.

Why is it possible to use both forms?

The manual says you can, no explanation why I have this alternative. I can’t imagine a plausible one other than taste. The bfavaretto spoke of a theory about helping the transition from Perl, a direct competitor at the time. It is a good theory, although I think it is a mistake to make this option. There is no gain to have this alternative. There are so many more radical things in the differences between these languages. But in fact a lot of PHP was done without much logic.

Using keys would be considered non-standard?

Strictly not.

Since you have never seen someone use, it is not who will start :) creates confusion, since the keys are usually used for something else, which alias already has more than one purpose, do not add one more. Leave the keys to use with what everyone is used to. Unless you find a good reason, which I doubt.

  • I thought I’d use the keys when I went to access the contents of a string, since in PHP, when using the brackets, it is also possible to access the index of the string (it would be to differentiate, but I also think it would be inventing too much fashion).

  • 3

    That would be just inventing fashion.

  • 1

    I read somewhere that accept {} would be a way to attract people who mess with perl.

  • 2

    @bfavaretto is possible, which will attract wrong people :) Who likes Perl will not change language, who finds PHP more interesting for something will adapt.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.