how to get the last character in a string in PHP

Question

Answers ( 1 )

    0
    2024-01-11T18:05:23+00:00

    To extract the last character from a string in PHP, there are several methods you can use:

    1. Using substr() Function: The substr() function is a built-in PHP function that returns a part of a string. You can use it to get the last character by specifying -1 as the start position, which represents the last character in the string.

      $string = "Hello";
      $lastChar = substr($string, -1);
      echo $lastChar; // Outputs: 'o'
      
    2. Using strlen() Function: First, find the length of the string using strlen() and then use substr() to get the last character.

      $string = "Hello";
      $lastChar = substr($string, strlen($string) - 1, 1);
      echo $lastChar; // Outputs: 'o'
      
    3. Accessing Like an Array: In PHP, strings can be accessed like arrays where each character is an element of the array. The last character can be accessed using the length of the string minus one.

      $string = "Hello";
      $lastChar = $string[strlen($string) - 1];
      echo $lastChar; // Outputs: 'o'
      
    4. Using mb_substr() for Multibyte Strings: If you are dealing with multibyte characters (like UTF-8), it's better to use mb_substr() to ensure proper handling of such characters.

      $string = "こんにちは"; // Japanese for "Hello"
      $lastChar = mb_substr($string, -1);
      echo $lastChar; // Outputs the last Japanese character
      

    Each of these methods is effective for getting the last character of a string in PHP. The choice of method may depend on the specific requirements of your application, such as the need to handle multibyte characters.

Leave an answer