PHP how to get the last character of the string.

In this blog, We are going to learn how to get the last character of the string.

Using substr() function

substr() Function to Get the Last Char of a String in PHP.
The built-in substr() function in PHP could get the substring of a string.

Syntax: substr(string_name, start_position, string_length_to_cut)

Parameters: The substr() function allows 3 parameters or arguments out of which two are mandatory and one is optional.

Lets Understand with an example

<?php
$test = "Justin Loves IceCream";
echo "Last character of String is: ".substr($test,-1);
?>

Output: The last character of String is: m

Using for Loop to Get the Last Char of a String in PHP

We can get the last char of a string by storing it into a new string and then fetch the last char with a for a loop. let’s begin,

Let’s Understand with an example:-

<?php 
$test = "This is a table";
$CharPosition = strlen($test) - 1;  
for ($n = $CharPosition; $n < strlen($test); $n++) {
    $result = $test[$n]; 
} 
echo "The last char of the string is $result.";
?>

Output: The last char of the string is e.

I hope that you found this Blog helpful. If you’ve any queries, please leave comments in the comment section.

Thanks for following and reading this blog.

PHP how to get the last character of the string.expoundsofttechsolution

PHP how to get the last character of the string.