PHP String Element
In this chapter you will learn:
- How to access PHP string element
- Syntax to access character in a string
- Example - Access single character in a string
Description
We can accessing characters within a PHP string with [] operator.
Syntax
We can access the individual characters of a string. To access a character at a particular position, or index , within a string, use:
$stringVariable= "a string value";
$character = $stringVariable[index];
We place the index between square brackets after the string variable name. String indices start from 0, so the first character in the string has an index of 0, the second has an index of 1, and so on.
Example
You can use [x] notation with strings to read or write individual characters.
<?PHP// j a v a 2 s .co m
$mystr = "java2s.com";
$mystr[0] = "H";
$mystr[12] = "!";
print $mystr;
?>
The code above generates the following result.
The first character in a string is numbered 0. A string of length 13 has its last character at position 12.
Next chapter...
What you will learn in the next chapter:
Home » PHP Tutorial » PHP String