Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP: string indexing

Tags:

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.

like image 298
codymanix Avatar asked May 19 '09 21:05

codymanix


People also ask

Can strings be indexed in PHP?

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] .

Is there indexing for strings?

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.

How do I find the index of a string in PHP?

The strpos() function finds the position of the first occurrence of a string inside another string.

How do I slice a string in PHP?

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.


1 Answers

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: Strings may also be accessed using braces, as in $str{42}, for the same purpose.

like image 129
Paolo Bergantino Avatar answered Oct 14 '22 17:10

Paolo Bergantino