24

What is the difference between $str[n] and $str{n}, given that $str is a string.

I noticed that both seem to work the same, except that {} does not occur in any documentation I found.

2

3 Answers 3

41

They are the same. However, they are getting rid of the {} syntax, so you should go with [].

According to the manual:

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. The functions substr() and substr_replace() can be used when you want to extract or replace more than 1 character.

Note: As of PHP 7.1.0, negative string offsets are also supported. These specify the offset from the end of the string. Formerly, negative offsets emitted E_NOTICE for reading (yielding an empty string) and E_WARNING for writing (leaving the string untouched).

Note: Prior to PHP 8.0.0, strings could also be accessed using braces, as in $str{42}, for the same purpose. This curly brace syntax was deprecated as of PHP 7.4.0 and no longer supported as of PHP 8.0.0.

Sign up to request clarification or add additional context in comments.

1 Comment

The braces {} are legacy from Perl hashes, and are being abandoned.
16

Be careful, $str[n] and $str{n} give n-th Byte of String, not n-th character of String. For multibyte encoding (UTF-8, etc.) one character doesn't need to be one Byte.

$str[0] – first Byte of string

mb_substr($str, 0, 1) – first character of string (including multibyte charsets)

http://php.net/mb_substr

1 Comment

It's worth noting that before PHP 5.6 the default encoding of the mbstring module is not UTF-8 — this can be changed in two places: within php scripts mb_internal_encoding('UTF-8'); -or- php.ini mbstring.internal_encoding='UTF-8'
2

I know this is an older question but I have to say that it is really important to understand that $str[n] is not returning the n-th char but the n-th byte. I just spent a whole day with this issue. There was a name $name = "Ömar" and the code retrieved the first letter with $name[0] which caused an error because of a malformed UTF-8 character (because "Ö", "Ä" etc need more than one byte)

TL;DR don't use indexing to retrieve chars from a string in PHP

2 Comments

The answer immediately above yours: "Be careful, $str[n] and $str{n} give n-th Byte of String, not n-th character of String."
I know, but I just wanted to give some insight as to which errors could be caused by that. Maybe someone encounters a "Malformed UTF-8" error and will be happy to find my answer :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.