PHP String Element

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/* ww  w  .  j  a  va2s . c o  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.





















Home »
  PHP Tutorial »
    Data Types »




Array
Array Associative
Array Util
ArrayObject
Data Types
Date
Date Format
DateTime
Number
String
String Escape
String Filter
String HTML
String Type
Timezone