How to get the last char of a string in PHP?

前端 未结 12 1433
说谎
说谎 2020-12-04 05:24

I need to get the last character of a string. Say I have \"testers\" as input string and I want the result to be \"s\". how can I do that in PHP?

12条回答
  •  Happy的楠姐
    2020-12-04 06:07

    As of PHP 7.1.0, negative string offsets are also supported. So, if you keep up with the times, you can access the last character in the string like this:

    $str[-1]
    

    DEMO

    At the request of a @mickmackusa, I supplement my answer with possible ways of application:

     string(1) "e"
    
    $str[-3]='.';
    var_dump($str);     // => string(6) "abc.ef"
    
    var_dump(isset($str[-4]));  // => bool(true)
    
    var_dump(isset($str[-10])); // => bool(false)
    

提交回复
热议问题