PHP Code to Extract the Last Character from a String

To get the last character from a string in PHP, you can use the substr() function or directly access the character using string indexing. Here are both methods:

Method 1: Using substr()

$string = "Hello, world!";

// Get the last character
$lastCharacter = substr($string, -1);

echo "Last character: " . $lastCharacter . "\n";

Method 2: Using String Indexing

$string = "Hello, world!";

// Get the last character
$lastCharacter = $string[strlen($string) - 1];

echo "Last character: " . $lastCharacter . "\n";

Both methods achieve the same result. In the first method, we use the substr() function with a negative index, which represents the last character of the string. In the second method, we use string indexing with strlen($string) - 1 to access the last character directly.

The output will be:

Last character: !

You can choose either method based on your preference or coding style.