Getting the first character of a string with $str[0]

前端 未结 9 1072
余生分开走
余生分开走 2020-11-28 21:04

I want to get the first letter of a string and I\'ve noticed that $str[0] works great. I am just not sure whether this is \'good practice\', as that notation is

相关标签:
9条回答
  • 2020-11-28 21:45

    Yes. Strings can be seen as character arrays, and the way to access a position of an array is to use the [] operator. Usually there's no problem at all in using $str[0] (and I'm pretty sure is much faster than the substr() method).

    There is only one caveat with both methods: they will get the first byte, rather than the first character. This is important if you're using multibyte encodings (such as UTF-8). If you want to support that, use mb_substr(). Arguably, you should always assume multibyte input these days, so this is the best option, but it will be slightly slower.

    0 讨论(0)
  • 2020-11-28 21:47

    My only doubt would be how applicable this technique would be on multi-byte strings, but if that's not a consideration, then I suspect you're covered. (If in doubt, mb_substr() seems an obviously safe choice.)

    However, from a big picture perspective, I have to wonder how often you need to access the 'n'th character in a string for this to be a key consideration.

    0 讨论(0)
  • 2020-11-28 21:47

    In case of multibyte (unicode) strings using str[0] can cause a trouble. mb_substr() is a better solution. For example:

    $first_char = mb_substr($title, 0, 1);
    

    Some details here: Get first character of UTF-8 string

    0 讨论(0)
  • 2020-11-28 21:51

    The {} syntax is deprecated as of PHP 5.3.0. Square brackets are recommended.

    0 讨论(0)
  • 2020-11-28 21:56
    $str = 'abcdef';
    echo $str[0];                 // a
    
    0 讨论(0)
  • 2020-11-28 21:58

    Lets say you just want the first char from a part of $_POST, lets call it 'type'. And that $_POST['type'] is currently 'Control'. If in this case if you use $_POST['type'][0], or substr($_POST['type'], 0, 1)you will get C back.

    However, if the client side were to modify the data they send you, from type to type[] for example, and then send 'Control' and 'Test' as the data for this array, $_POST['type'][0] will now return Control rather than C whereas substr($_POST['type'], 0, 1) will simply just fail.

    So yes, there may be a problem with using $str[0], but that depends on the surrounding circumstance.

    0 讨论(0)
提交回复
热议问题