PHP: Get nth character from end of string

Posted on

PHP: Get nth character from end of string – Here in this article, we will share some of the most common and frequently asked about PHP problem in programming with detailed answers and code samples. There’s nothing quite so frustrating as being faced with PHP errors and being unable to figure out what is preventing your website from functioning as it should like php and string . If you have an existing PHP-based website or application that is experiencing performance issues, let’s get thinking about PHP: Get nth character from end of string.

I’m sure there must be an easy way to get nth character from the end of string.

For example:

$NthChar = get_nth('Hello', 3); // will result in $NthChar='e'

Solution :

Just do this

  $rest = substr("abcdef", -3, 1); // returns 'd'

Like this:

function get_nth($string, $index) {
    return substr($string, strlen($string) - $index - 1, 1);
}

from substr examples

// Accessing single characters in a string
// can also be achieved using "square brackets"

thus:

$str = "isogram";
echo $str[-1]; // m
echo $str[-2]; // a
echo $str[-3]; // r
<?php
function get_nth($string, $offset) {
    $string = strrev($string); //reverse the string
    return $string[$offset];
}

$string = 'Hello';
echo get_nth($string, 3);

As $string[3] will give you the 3rd offset of the string, but you want it backwards, you need to string reverse it.


Edit:

Despite other answers (posted after mine) are using substring, and it can be a one liner, it is hardly readable to have substr($string, -2, 1), then just reverse the string and output the offset.

substr($string, -3);//returns 3rd char from the end of the string