PHP String Element

In this chapter you will learn:

  1. How to access PHP string element
  2. Syntax to access character in a string
  3. 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:

  1. What is assignment operator
  2. PHP assignment operators
Home » PHP Tutorial » PHP String
PHP String
PHP Single vs double quotation string
PHP String Escape Sequences
PHP Variable substitution in String
PHP String Element