PHP does not differentiate between characters or strings. In a PHP program a character is a string with length 1 and a string is a collection of more than one characters. Character and string indexes begin with integer value 0 and end at 1 less than the length of string. A string with ‘N’ count of characters will give 0 index to its first character and ‘N-1’ index to its last character
For example
$my_char=’a’;
The start and end index of $my_char is 0 since length of this string is 1
$my_str=’hello world’;
The start index of $my_str is 0 for ‘h’ and 10 for ‘d’ the last character of the string. The length of this string is 11.
Character and String indexes for String Handling
To traverse each individual character in a string you can use the index of that character in curly braces. It must be placed immediately after the variable name for the string.
Consider the following example
<?php $my_str='Hello World'; for ($ctr=0; $ctr<strlen($my_str);$ctr++) { $i=$ctr+1; $char=$my_str{$ctr}; echo "Character No-$i is $char<BR>"; } ?>
The output is
Character No-1 is H Character No-2 is e Character No-3 is l Character No-4 is l Character No-5 is o Character No-6 is Character No-7 is W Character No-8 is o Character No-9 is r Character No-10 is l Character No-11 is d
$char=$my_str{$ctr};
In the example give here the above statement is used to extract one character at a time from the string by using the current index in curly braces with string variable name. This is the technique of using characters and string indexes to manipulate individual characters constituting a string.
Character and string indexes give flexibility to a programmer for string manipulation. It can be used to reverse a string, count specific characters or do some conditional processing based on occurrence of a character. PHP offers a number of inbuilt string handling functions. But with character and string indexes a programmer can better understand the working of strings in PHP.