Getting String Characters in PHP
Let's say we have some string. Each
character in this string has its own serial
number: the first character is number 0, the second
character is number 1, the third character is number
2, and so on.
If necessary, you can access a specific character of the string by its number. To do this, write the variable name, then after this name, put square brackets and inside these brackets specify the character number.
Let's look at an example. Let's say we are given the following string:
<?php
$str = 'abcde';
?>
Let's output some characters of this string:
<?php
$str = 'abcde';
echo $str[0]; // outputs 'a'
echo $str[1]; // outputs 'b'
echo $str[2]; // outputs 'c'
?>
When getting a character, you can also
use negative values.
In this case, characters will be counted
from the end. Here, the last
character has the number -1.
Let's try:
<?php
$str = 'abcde';
echo $str[-1]; // outputs 'e'
echo $str[-2]; // outputs 'd'
echo $str[-5]; // outputs 'a'
?>
You can also change characters of a string by their number. Let's change the zero character as an example:
<?php
$str = 'abcde';
$str[0] = '+';
echo $str; // outputs '+bcde'
?>
The character number can also be stored in a variable:
<?php
$str = 'abcde';
$num = 3; // character number in a variable
echo $str[$num]; // outputs 'd'
?>
Given a string:
<?php
$str = 'abcde';
?>
By accessing individual characters of this
string, output to the screen
the character 'a', the character 'c', the character 'e'.
Given a string:
<?php
$str = 'abcde';
?>
Output its last character.
Given a string:
<?php
$str = 'abcde';
?>
By accessing individual characters of this string,
write into a new variable the characters of this
string in reverse order, i.e., 'edcba'.
Given variables:
<?php
$str = 'abcde';
$num = 3;
?>
Output to the screen the character whose number
is stored in the variable $num.