How to Access a Character for a Position from a String in PHP?

How to Access a Character for a Position from a String in PHP?

  • PHP
  • 1 min read

In PHP, a character can be accessed by using the position of the character within the string, and the position will be written in { } with string variable name. The index of the string is started from 0. So the index for the first character of a string is 0.

Here is an example for accessing the position of the third character of a string "Kolkata":

<html>
<body>
<?php
$a="Kolkata";
$b=$a{2};
echo $b;
?>
</body>
</html>

Output: l

Here is an example for modifying a character for a position of a string "Kolkata in India":

<html>
<body>
<?php
$a="Kolkata in India";
$a{0}='K';//here 'K' is assigned to the first position 
echo $a;
?>
</body>
</html>

Output: Kolkata in India

See also: