• 13

A PHP Error was encountered

Severity: Notice

Message: Undefined index: userid

Filename: views/question.php

Line Number: 191


File: /home/prodcxja/public_html/questions/application/views/question.php
Line: 191
Function: _error_handler

File: /home/prodcxja/public_html/questions/application/controllers/Questions.php
Line: 433
Function: view

File: /home/prodcxja/public_html/questions/index.php
Line: 315
Function: require_once

name Punditsdkoslkdosdkoskdo

PHP $string{0} vs. $string[0];

In PHP you can access characters of strings in a few different ways, one of which is substr(). You can also access the Nth character in a string with curly or square braces, like so:

$string = 'hello';

echo $string{0}; // h
echo $string[0]; // h

My question is, is there a benefit of one over the other? What's the difference between {} and []?


use $string[0], the other method (braces) is being deprecated in PHP6 (src)

Note: Strings may also be accessed using braces, as in $str{42}, for the same purpose. However, this syntax is deprecated as of PHP 6. Use square brackets instead.

  • 42
Reply Report

There is no difference. Owen's answer is outdated, the latest version of PHP Manual no longer states that it is deprecated §:

Characters within strings may be accessed and modified by specifying the zero-based offset of the desired character after the string using square array brackets, as in $str[42]. Think of a string as an array of characters for this purpose. [...]

Note: Strings may also be accessed using braces, as in $str{42}, for the same purpose.

However it seems that more people/projects use [], and that many people don't even know {} is possible. If you need to share your code publicly or with people who don't know the curly brace syntax, it may be beneficial to use [].

UPDATED : accessing string characters with {} is deprecated, use [] instead.

  • 19
Reply Report
      • 1
    • I prefer curly braces because it makes it visually clear that I'm accessing a char from a string variable, not a value from an array. On some level, that's the same thing, but on the code level, it makes it visually nicer.

Yes, there's no difference. This language quirk has some history...

Originally, the curly brace syntax was intended to replace the square bracket syntax which was going to be deprecated:


Later that policy was reversed, and the square brackets syntax was preferred instead:


and even later, the curly braces one was going to be deprecated:


As of this writing, it seems that the deprecation has been withdrawn as well and they are just considered two alternative syntaxes:


  • 3
Reply Report

Warm tip !!!

This article is reproduced from Stack Exchange / Stack Overflow, please click

Trending Tags

Related Questions