To find the k-th character in a string in PHP, you can use the substr
function.
The substr
function allows you to extract a part of a string, starting from a specific index and with a specific length.
To extract a single character from a string, you can pass the starting index and a length of 1 to the substr
function.
Here's an example of how to find the 5th character in a string:
main.php121 chars7 lines
In this example, the $str
variable contains the string "Hello, world!". The $k
variable is set to 4, which is the index of the 5th character in the string, as indexing starts from 0.
The substr
function extracts a substring starting from the 4th index and with a length of 1, which corresponds to the 5th character in the original string.
The $character
variable contains the extracted character, which is then outputted to the screen using the echo
statement.
gistlibby LogSnag