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.
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.
They are the same. However, they are getting rid of the {}
syntax, so you should go with []
.
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 functionssubstr()
andsubstr_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) andE_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.
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)
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