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.
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] .
String indexing in Python is zero-based, so the very first character in the string would have an index of 0 , 00:30 and the next would be 1 , and so on. The index of the last character will be the length of the string minus one.
The strpos() function finds the position of the first occurrence of a string inside another string.
PHP: substr() function The substr() function used to cut a part of a string from a string, starting at a specified position. The input string. Refers to the position of the string to start cutting. A positive number : Start at the specified position in the string.
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 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: Strings may also be accessed using braces, as in
$str{42}
, for the same purpose.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With